package io.finer.erp.jeecg.stock.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.constant.WarehouseConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.finer.erp.jeecg.bas.entity.BasCategoryLabel;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.BasMeasureUnit;
import io.finer.erp.jeecg.bas.entity.BasProductFormula;
import io.finer.erp.jeecg.bas.entity.BasSupplier;
import io.finer.erp.jeecg.bas.entity.BasWarehouse;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProduct;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.entity.ZzDevice;
import io.finer.erp.jeecg.bas.entity.ZzDeviceType;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.mapper.BasCustomerMapper;
import io.finer.erp.jeecg.bas.mapper.BasMaterialCategoryMapper;
import io.finer.erp.jeecg.bas.service.IBasCategoryLabelService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialLogService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.IBasProductFormulaService;
import io.finer.erp.jeecg.bas.service.IBasSupplierService;
import io.finer.erp.jeecg.bas.service.IBasWarehouseService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProductService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceService;
import io.finer.erp.jeecg.bas.service.IZzDeviceTypeService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.stock.entity.ErpSysUser;
import io.finer.erp.jeecg.stock.entity.SaleOrderDTO;
import io.finer.erp.jeecg.stock.entity.StkInventory;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.entity.StkProcessingOrder;
import io.finer.erp.jeecg.stock.entity.StkProcessingRecord;
import io.finer.erp.jeecg.stock.entity.StkTray;
import io.finer.erp.jeecg.stock.entity.StkTrayDetail;
import io.finer.erp.jeecg.stock.mapper.ErpUserMapper;
import io.finer.erp.jeecg.stock.mapper.ScanMapper;
import io.finer.erp.jeecg.stock.mapper.StkIoBillMapper;
import io.finer.erp.jeecg.stock.service.IScan3rdService;
import io.finer.erp.jeecg.stock.service.IStkInventoryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IStkIoMaterialLogService;
import io.finer.erp.jeecg.stock.service.IStkPickUpBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpEntryService;
import io.finer.erp.jeecg.stock.service.IStkProcessingOrderService;
import io.finer.erp.jeecg.stock.service.IStkProcessingRecordService;
import io.finer.erp.jeecg.stock.service.IStkTrayDetailService;
import io.finer.erp.jeecg.stock.service.IStkTrayService;
import io.finer.erp.jeecg.stock.util.ScanUtil;
import io.finer.erp.jeecg.stock.vo.SaleOutVO;
import io.finer.erp.jeecg.stock.vo.ScanIO;
import io.finer.erp.jeecg.stock.vo.TrayVO;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class Scan3rdServiceImpl implements IScan3rdService {
	@Autowired
	private IZrkQzOrderService mesService;
	@Autowired
	private IZrkShoporderService zrkShopOrderService;
	@Autowired
	private IStkIoBillService billService;
	@Autowired
	private IStkIoBillEntryService billEntryService;
	@Autowired
	private StkIoBillMapper billMapper;
	@Autowired
	private IZzShoporderService shopOrderService;
	@Autowired
	private IStkPickUpBillService pickUpBillService;
	@Autowired
	private IStkPickUpEntryService pickUpEntryService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private BasMaterialCategoryMapper categoryMapper;
	@Autowired
	private IStkInventoryService inventoryService;
	@Autowired
	private BasCustomerMapper customerMapper;
	@Autowired
	private ScanMapper scanMapper;
	@Autowired
	private IStkTrayService trayService;
	@Autowired
	private IStkTrayDetailService trayDetailService;
	@Autowired
	private IBasMaterialTempService materialTempService;
	@Autowired
	private IZzDeviceTypeService deviceTypeService;
	@Autowired
	private IBasMeasureUnitService unitService;
	@Autowired
	private IZzDeviceService deviceService;
	@Autowired
	private IStkIoMaterialLogService logService;
	@Autowired
	private IZrkOrderProductService productService;
	@Autowired
	private IStkProcessingOrderService processingService;
	@Autowired
	private IStkProcessingRecordService processingRecordService;
	@Autowired
	private IBasProductFormulaService formulaService;
	@Autowired
	private ErpUserMapper userMapper;
	@Autowired
	private IBasMaterialLogService materialLogService;
	@Autowired
	private ISysBaseAPI baseApi;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IBasWarehouseService warehouseService;
	@Autowired
	private IBasSupplierService supplierService;
	@Autowired
	private IBasCategoryLabelService labelService;
	
	private static final String BILL_SUBMIT_STATUS = "13";

	@Override
	public Result<?> getProcessMes(String processId) {
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		query.eq(ZrkQzOrder::getProcessId, processId);
		query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newLinkedList("3", "4", "5"));
		query.orderByDesc(ZrkQzOrder::getCreateTime);
		query.last(" limit 500 ");
		List<ZrkQzOrder> list = this.mesService.list(query);
		list = ScanUtil.changeListToVector(list);
		return Result.ok(list);
	}

	@Override
	public Result<Object> getOrder(String userId, Integer orderType, Result<Object> result, String inOutType) {
		switch(orderType) {
		case 0://商城订单
			LambdaQueryWrapper<ZrkShoporder> zrkShoporderQuery = new LambdaQueryWrapper<>();
			zrkShoporderQuery.eq(ZrkShoporder::getOrderStatus, 2);//已支付待发货
			zrkShoporderQuery.orderByDesc(ZrkShoporder::getCreateTime);
			IPage<ZrkShoporder> page = new Page<>(1, 100);
			page = this.zrkShopOrderService.page(page, zrkShoporderQuery);
			List<ZrkShoporder> zrkShoporderList = page.getRecords();
			zrkShoporderList = ScanUtil.changeListToVector(zrkShoporderList);
			return Result.ok(zrkShoporderList);
		case 1://工单
			LambdaQueryWrapper<ZzShoporder> shopQuery = new LambdaQueryWrapper<>();
			shopQuery.ne(ZzShoporder::getWoStatus, 4);
			shopQuery.orderByDesc(ZzShoporder::getCreateTime);
			List<ZzShoporder> shopOrderList = this.shopOrderService.list(shopQuery);
			return Result.ok(ScanUtil.changeListToVector(shopOrderList));
		case 2://采购单
			List<StkIoBill> billList = this.billService.pdaGetPurchaseOrder();
			List<StkIoBill> newBillList = ScanUtil.changeListToVector(billList);
			return Result.ok(ScanUtil.changeListToVector(newBillList));
		case 3://MES单
			if(StringUtils.isBlank(inOutType)) {
				return Result.error("未传入出入库类型");
			}
			return Result.ok(getMesList(inOutType));
		}
		return null;
	}
	
	/**
	 * @Description 根据出入库类型获取对应的MES单据
	 * @param inOutType
	 * @return
	 * Create at: 2021-01-26 10:23:29
	 * @author: duany
	 * Revision:
	 *    2021-01-26 10:23:29 - first revision by duany
	 *        
	 */
	private List<ZrkQzOrder> getMesList(String inOutType){
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newLinkedList("5"));
		query.orderByDesc(ZrkQzOrder::getUpdateTime);
		
		List<String> processList = null;
		if("1992".equals(inOutType) || "2991".equals(inOutType)) {
			processList = CollUtil.newArrayList(MaterialConstant.PROCESS_COMPOUND);
		}
		if("1993".equals(inOutType) || "2992".equals(inOutType)) {
			processList = CollUtil.newArrayList(MaterialConstant.PROCESS_PART);
		}
		if("1991".equals(inOutType) || "2993".equals(inOutType)) {
			processList = CollUtil.newArrayList(MaterialConstant.PROCESS_CUTTING_BIG, MaterialConstant.PROCESS_CUTTING_NORMAL);
		}
		if("1994".equals(inOutType)) {
			processList = CollUtil.newArrayList(MaterialConstant.PROCESS_COMPOUND
					, MaterialConstant.PROCESS_CUTTING_BIG
					, MaterialConstant.PROCESS_CUTTING_NORMAL
					, MaterialConstant.PROCESS_PART);
		}
		if(null != processList) {
			query.in(ZrkQzOrder::getProcessId, processList);
			return this.mesService.list(query);
		}
		return null;
	}

	@Override
	public Boolean checkOutComplete(String mesId) {
		List<StkPickUpBill> billList = this.pickUpBillService.getByMesId(mesId);
		Map<String, StkPickUpBill> pickUpBillMap = MapUtil.newHashMap();
		ZrkQzOrder mesOrder = mesService.getById(mesId);
		if(null == mesOrder) {
			return Boolean.FALSE;
		}
		if(CollUtil.isEmpty(billList)) {
			return Boolean.FALSE;
		}
		//查询提货单明细
		List<StkPickUpEntry> entryList = CollUtil.newArrayList();
		List<String> outMaterialIdList = CollUtil.newArrayList();
		List<String> outCategoryIdList = CollUtil.newArrayList();
		Map<String, BigDecimal> pickUpNumMap = Maps.newHashMap();
		for (StkPickUpBill bill : billList) {
			List<StkPickUpEntry> entrys = this.pickUpEntryService.selectByMainId(bill.getId());
			if(CollUtil.isEmpty(entrys)) {
				continue;
			}
			pickUpBillMap.put(bill.getId(), bill);
			entryList.addAll(entrys);
			for (StkPickUpEntry entry : entrys) {
				String materialId = entry.getMaterialId();
				if(StringUtils.isNotBlank(materialId)) {
					outMaterialIdList.add(materialId);
					continue;
				}
				String categoryId = entry.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)) {
					outCategoryIdList.add(categoryId);
					BigDecimal number = entry.getNumber();
					BigDecimal totalNum = pickUpNumMap.get(categoryId);
					if(number == null) {
						continue;
					}
					if(null == totalNum) {
						pickUpNumMap.put(categoryId, number);
					} else {
						totalNum = totalNum.add(number);
					}
				}
			}
		}
		//查询出入库单及相关明细
		List<StkIoBill> ioBillList = this.billService.getBillBySourceId(mesId);
		if(CollUtil.isEmpty(ioBillList)) {
			return Boolean.FALSE;
		}
		List<StkIoBillEntry> ioEntryList = CollUtil.newArrayList();
		for (StkIoBill ioBill : ioBillList) {
			if(!StrUtil.startWith(ioBill.getStockIoType(), "2")) {
				continue;
			}
			List<StkIoBillEntry> ioEntrys = billEntryService.selectByMainId(ioBill.getId());
			ioEntryList.addAll(ioEntrys);
		}
		if(CollUtil.isEmpty(ioEntryList)) {
			return Boolean.FALSE;
		}
		
		//获取工序ID
		String processId = mesOrder.getProcessId();
		if(StrUtil.isBlank(processId)) {
			return Boolean.FALSE;
		}
		//如果是复合工序
		if(processId.equals(MaterialConstant.PROCESS_COMPOUND)) {
			
		}
		//如果是分切工序
		if(processId.equals(MaterialConstant.PROCESS_PART)) {
			
		}
		//如果是切张工序
		if(processId.equals(MaterialConstant.PROCESS_CUTTING_BIG) || processId.equals(MaterialConstant.PROCESS_CUTTING_NORMAL)) {
			
		}
		//计算提货是否完成
		Map<String, BigDecimal> map = CollUtil.newHashMap();
		int mateNum = 0;
		int cateNum = 0;
		for (StkIoBillEntry stkIoBillEntry : ioEntryList) {
			String materialId = stkIoBillEntry.getMaterialId();
			if(outMaterialIdList.contains(materialId)) {
				mateNum ++;
				continue;
			}
			BasMaterial material = this.materialService.getById(materialId);
			String cateId = material.getCategoryId();
			if(outCategoryIdList.contains(cateId)) {
				cateNum ++;
			}
			BigDecimal decimal = map.get(cateId);
			if(null == decimal) {
				map.put(cateId, decimal);
			} else {
				decimal = decimal.add(stkIoBillEntry.getQty());
			}
		}
		if(mateNum != outMaterialIdList.size()) {
			return Boolean.FALSE;
		}
		if(cateNum != outCategoryIdList.size()) {
			return Boolean.FALSE;
		}
		BigDecimal percent = new BigDecimal("0.95");
		for (String key : pickUpNumMap.keySet()) {
			BigDecimal num = pickUpNumMap.get(key);
			
			BigDecimal num1 = map.get(key);
			if(null == num1) {
				return Boolean.FALSE;
			}
			if(num1.divide(num, 5, BigDecimal.ROUND_HALF_UP).compareTo(percent) < 0) {
				return Boolean.FALSE;
			}
		}
		mesOrder.setMesOrderStatus("2");
		this.mesService.updateById(mesOrder);
		for (StkPickUpBill bill : billList) {
			bill.setBillStatus("2");
			this.pickUpBillService.updateById(bill);
		}
		for (StkPickUpEntry entry : entryList) {
			entry.setIsOut("1");
			this.pickUpEntryService.updateById(entry);
		}
		
		return Boolean.TRUE;
	}

	@Override
	public Result<?> getInOutMes(Integer type, Integer inOutType) {
		if(0 == type) {
			LambdaQueryWrapper<ZrkQzOrder> que = new LambdaQueryWrapper<>();
			que.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newArrayList("4", "5", "3", "6"));
			List<ZrkQzOrder> list = this.mesService.list(que);
			return Result.ok(list);
		}
		
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		//复合
		if(1 == type) {
			query.eq(ZrkQzOrder::getProcessId, MaterialConstant.PROCESS_COMPOUND);
		}
		//分切
		if(2 == type) {
			query.eq(ZrkQzOrder::getProcessId, MaterialConstant.PROCESS_PART);
		}
		//切张
		if(3 == type) {
			query.in(ZrkQzOrder::getProcessId, CollUtil.newArrayList(MaterialConstant.PROCESS_CUTTING_BIG, MaterialConstant.PROCESS_CUTTING_NORMAL));
		}
		//入库
		if(1 == inOutType) {
			query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newArrayList("3","4", "5", "6"));
			query.isNull(ZrkQzOrder::getParentId);
		}
		//出库
		if(2 == inOutType) {
			query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newArrayList("3", "2", "1", "6"));
			query.isNull(ZrkQzOrder::getParentId);
		}
		query.orderByDesc(ZrkQzOrder::getCreateTime);
		query.last(" limit 200 ");
		List<ZrkQzOrder> list = this.mesService.list(query);
		list = ScanUtil.changeListToVector(list);
		return Result.ok(list);
	}

	@Override
	public Result<?> getMesCategory(String mesId) {
		ZrkQzOrder mes = this.mesService.getById(mesId);
		String categoryId = mes.getMaterialId();
		List<BasMaterialCategory> childList = categoryMapper.getAllChildCategory(categoryId);
		BasMaterialCategory category = categoryMapper.selectById(categoryId);
		List<BasMaterialCategory> list = CollUtil.newArrayList(category);
		if(CollUtil.isNotEmpty(childList)) {
			list.addAll(childList);
		}
		return Result.ok(list);
	}

	@Override
	public Result<?> seeMaterial(String code) {
		List<String> resultStringList = Lists.newLinkedList();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			resultStringList.add("物料不存在");
			return Result.ok(resultStringList);
		}
		resultStringList.add("物料已录入");
		String materialId = material.getId();
		LambdaQueryWrapper<StkInventory> inQuery = new LambdaQueryWrapper<>();
		inQuery.eq(StkInventory::getMaterialId, materialId);
		inQuery.orderByDesc(StkInventory::getCreateTime);
		List<StkInventory> inventorys = inventoryService.list(inQuery);
		if(CollUtil.isEmpty(inventorys)) {
			resultStringList.add("物料没有库存记录");
		} else {
			StkInventory inventory = inventorys.get(0);
			resultStringList.add("物料库存号为" + inventory.getBatchNo());
		}
		LambdaQueryWrapper<StkIoBillEntry> entryQuery = new LambdaQueryWrapper<>();
		entryQuery.eq(StkIoBillEntry::getMaterialId, materialId);
		int count = this.billEntryService.count(entryQuery);
		if(0 == count) {
			resultStringList.add("物料没有出入库记录");
		}
		List<StkIoBill> billList = this.billMapper.getIoBillByMaterialAsc(materialId);
		
		if(CollUtil.isNotEmpty(billList)) {
			List<BasWarehouse> warehouseList = this.warehouseService.list();
			Map<String, BasWarehouse> warehouseMap = Maps.newHashMap();
			for (BasWarehouse basWarehouse : warehouseList) {
				warehouseMap.put(basWarehouse.getId(), basWarehouse);
			}
			List<String> midList = Lists.newArrayList();
			for (StkIoBill bill : billList) {
				midList.add(bill.getId());
			}
			LambdaQueryWrapper<StkIoBillEntry> query = new LambdaQueryWrapper<>();
			query.in(StkIoBillEntry::getMid, midList);
			query.orderByAsc(StkIoBillEntry::getId);
			List<StkIoBillEntry> entryList = this.billEntryService.list(query);
			Map<String, List<StkIoBillEntry>> entryMap = Maps.newHashMap();
			if(CollUtil.isNotEmpty(entryList)) {
				for (StkIoBillEntry entry : entryList) {
					String mid = entry.getMid();
					List<StkIoBillEntry> list = entryMap.get(mid);
					if(null == list) {
						list = CollUtil.newArrayList(entry);
					} else {
						list.add(entry);
					}
					entryMap.put(mid, list);
				}
			}
			for (StkIoBill bill : billList) {
				String billId = bill.getId();
				Date billTime = bill.getCreateTime();
				String type = bill.getStockIoType();
				String timeStr = DateUtil.formatDateTime(billTime);
				List<StkIoBillEntry> billEntryList = entryMap.get(billId);
				StringBuffer buffer = new StringBuffer();
				switch(type) {
					case "101":
						buffer.append(timeStr).append("采购入库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "201":
						buffer.append(timeStr).append("物料销售出库，编码为").append(bill.getBillNo());
						break;
					case "1991":
						buffer.append(timeStr).append("切张入库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "1992":
						buffer.append(timeStr).append("复合入库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "1993":
						buffer.append(timeStr).append("分切入库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "2991":
						buffer.append(timeStr).append("复合出库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "2992":
						buffer.append(timeStr).append("分切出库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "2993":
						buffer.append(timeStr).append("切张出库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "1994":
						buffer.append(timeStr).append("生产退库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "1997"://胶水入库
						buffer.append(timeStr).append("制胶入库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "2997"://胶水出库
						buffer.append(timeStr).append("制胶出库，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",仓库为").append(warehouse.getName());
									}
									break;
								}
							}
						}
						break;
					case "301"://库存调拨
						buffer.append(timeStr).append("库存调拨，编码为").append(bill.getBillNo());
						if(CollUtil.isNotEmpty(billEntryList)) {
							for (StkIoBillEntry entry : billEntryList) {
								if(StringUtils.equals(materialId, entry.getMaterialId())) {
									BasWarehouse warehouse = warehouseMap.get(entry.getWarehouseId());
									if(null != warehouse) {
										buffer.append(",调出仓库为").append(warehouse.getName());
									}
									String inWarehouseId = entry.getInWarehouseId();
									BasWarehouse inWarehouse = warehouseMap.get(inWarehouseId);
									if(null != inWarehouse) {
										buffer.append(",调入仓库为").append(inWarehouse.getName());
									}
									break;
								}
							}
						}
						break;
				}
				resultStringList.add(buffer.toString());
			}
		}
		
		return Result.ok(resultStringList);
	}

	@Override
	public Result<?> getMesCustomer(String orderId) {
		ZrkQzOrder mes = this.mesService.getById(orderId);
		List<String> customerIds = CollUtil.newArrayList();
		String ortherIdStr = UUID.randomUUID().toString();
		customerIds.add(ortherIdStr);
		if(null != mes) {
			String orderIds = mes.getOrderProcessId();
			if(StringUtils.isNotBlank(orderIds)) {
				String[] orderIdArray = StringUtils.split(orderIds, ",");
				List<String> orderIdList = CollUtil.newArrayList(orderIdArray);
				LambdaQueryWrapper<ZzShoporder> zsQuery = new LambdaQueryWrapper<>();
				zsQuery.in(ZzShoporder::getId, orderIdList);
				List<ZzShoporder> list = this.shopOrderService.list(zsQuery);
				List<String> orderNoList = CollUtil.newArrayList();
				orderNoList.add(ortherIdStr);
				if(CollUtil.isNotEmpty(list)) {
					Iterator<ZzShoporder> iterator = list.iterator();
					while(iterator.hasNext()) {
						ZzShoporder zzShoporder = iterator.next();
						orderNoList.add(zzShoporder.getOrderNo());
					}
				}
				LambdaQueryWrapper<ZrkShoporder> zrkQuery = new LambdaQueryWrapper<>();
				zrkQuery.in(ZrkShoporder::getOrderNo, orderNoList);
				List<ZrkShoporder> orderList = this.zrkShopOrderService.list(zrkQuery);
				if(CollUtil.isNotEmpty(orderList)) {
					Iterator<ZrkShoporder> iterator = orderList.iterator();
					while(iterator.hasNext()) {
						ZrkShoporder zrkOrder = iterator.next();
						customerIds.add(zrkOrder.getCustomerId());
					}
				}
			}
			
		}
		LambdaQueryWrapper<BasCustomer> query = new LambdaQueryWrapper<>();
		query.in(BasCustomer::getId, customerIds);
		List<BasCustomer> list = this.customerMapper.selectList(query);
		return Result.ok(list);
	}
	
	
	public Boolean checkIsFomula(List<BasMaterial> materials, String mesId) {
//		ZrkQzOrder mes = this.mesService.getById(mesId);
//		if(null != mes) {
//			String formulaId = mes.getFormulaId();
//			String processId = mes.getProcessId();
//			if(StringUtils.isNotBlank(formulaId) && StringUtils.isNotBlank(processId)) {
//				Boolean fhFlag = Boolean.FALSE;
//				Boolean fqFlag = Boolean.FALSE;
//				Boolean qzFlag = Boolean.FALSE;
//				if(processId.equals(MaterialConstant.PROCESS_COMPOUND)) {
//					fhFlag = Boolean.TRUE;
//				}
//				if(processId.equals(MaterialConstant.PROCESS_CUTTING_BIG) || processId.equals(MaterialConstant.PROCESS_CUTTING_NORMAL)) {
//					qzFlag = Boolean.TRUE;
//				}
//				if(processId.equals(MaterialConstant.PROCESS_PART)) {
//					fqFlag = Boolean.TRUE;
//				}
//				List<BasPfMaterial> pfList = pfMaterialService.selectByMainId(formulaId);
//				List<String> categoryIdList = CollUtil.newArrayList();
//				List<String> supplierIdList = CollUtil.newArrayList();
//				for (BasPfMaterial basPfMaterial : pfList) {
//					String categoryId = basPfMaterial.getPfName();
//					String supplierId = basPfMaterial.getCorporate();
//					
//					categoryIdList.add(categoryId);
//					supplierIdList.add(supplierId);
//				}
//				for (BasMaterial material : materials) {
//					String mformulaId = material.getFormulaId();
//					if(StringUtils.isBlank(mformulaId)) {
//						continue;
//					}
//					if(mformulaId.equals(formulaId)) {
//						continue;
//					}
//					String categoryId = material.getCategoryId();
//					String supplierId = material.getSupplier();
////					if(fhFlag) {
////						if(!categoryIdList.contains(categoryId)) {
////							return Boolean.FALSE;
////						}
////					}
////					if(fqFlag || qzFlag) {
////						
////						if(!supplierIdList.contains(supplierId)) {
////							return Boolean.FALSE;
////						}
////					}
//				}
//			}
//		}
		
		return Boolean.TRUE;
	}

	@Override
	public Result<?> getMaterialOrder(String code) {
		Boolean isTray = ScanUtil.isTrayCode(code);
		if(isTray) {
			StkTray tray = this.trayService.lambdaQuery().eq(StkTray::getCode, code).one();
			if(null != tray) {
				List<String> materialIds = Lists.newArrayList();
				List<StkTrayDetail> details = this.trayDetailService.selectByMainId(tray.getId());
				if(CollUtil.isNotEmpty(details)) {
					for (StkTrayDetail detail : details) {
						materialIds.add(detail.getMaterialId());
					}
				}
				if(CollUtil.isEmpty(materialIds)) {
					List<SaleOrderDTO> orderList = CollUtil.newArrayList();
					return Result.ok(orderList);
				}
				List<BasMaterial> materials = this.materialService.lambdaQuery().in(BasMaterial::getId, materialIds).list();
				if(CollUtil.isEmpty(materials)) {
					List<SaleOrderDTO> orderList = CollUtil.newArrayList();
					return Result.ok(orderList);
				}
				List<String> codes = Lists.newArrayList();
				List<String> categoryIds = Lists.newArrayList();
				for (Iterator<BasMaterial> iterator = materials.iterator(); iterator.hasNext();) {
					BasMaterial material = iterator.next();
					String categoryId = material.getCategoryId();
					if(!categoryIds.contains(categoryId)) {
						List<String> categoryList = Lists.newArrayList();
						categoryList.add(categoryId);
						categoryList = getParentCategory(categoryList, categoryId);
						categoryIds.addAll(categoryList);
					}
					codes.add(material.getCode());
				}
				List<BasMaterialTemp> temps = this.materialTempService.lambdaQuery().in(BasMaterialTemp::getCode, codes).list();
				List<String> customerIds = Lists.newArrayList();
				if(CollUtil.isNotEmpty(temps)) {
					for (BasMaterialTemp temp : temps) {
						String customerId = temp.getCustomerId();
						if(StringUtils.isNotBlank(customerId)) {
							customerIds.add(customerId);
						}
					}
				}
				StringBuffer customerIdStrBuffer = new StringBuffer("");
				if(CollUtil.isNotEmpty(customerIds)) {
					customerIdStrBuffer.append("('");
					customerIdStrBuffer.append(CollUtil.join(customerIds, "','"));
					customerIdStrBuffer.append("')");
				}
				StringBuffer categoryIdStrBuffer = new StringBuffer("('");
				categoryIdStrBuffer.append(CollUtil.join(categoryIds, "','"));
				categoryIdStrBuffer.append("')");
				List<SaleOrderDTO> orderList = this.scanMapper.getZrkShoporderByCategoryIds(categoryIdStrBuffer.toString(), customerIdStrBuffer.toString());
				return Result.ok(orderList);
			}
		} else {
			BasMaterialTemp temp = this.materialTempService.getByCode(code);
			if(null == temp) {
				List<SaleOrderDTO> orderList = CollUtil.newArrayList();
				return Result.ok(orderList);
			}
			String customerId = temp.getCustomerId();
			String categoryId = temp.getCategoryId();
			List<String> categoryList = Lists.newArrayList();
			categoryList.add(UUID.randomUUID().toString());
			categoryList.add(categoryId);
			categoryList = getParentCategory(categoryList, categoryId);
			List<String> categoryIdList = Lists.newArrayList();
			for (String string : categoryList) {
				categoryIdList.add(StrUtil.builder("'", string, "'").toString());
			}
			StringBuffer categoryBuffer = new StringBuffer(" ( ");
			categoryBuffer.append(CollUtil.join(categoryIdList, ","));
			categoryBuffer.append(" ) ");
			StringBuffer customerIdStrBuffer = new StringBuffer("");
			if(StringUtils.isNotBlank(customerId)) {
				customerIdStrBuffer.append(" ('").append(customerId).append("') ");
			}
			List<SaleOrderDTO> orderList = this.scanMapper.getZrkShoporderByCategoryIds(categoryBuffer.toString(), customerIdStrBuffer.toString());
			return Result.ok(orderList);
		}
		return Result.ok(Lists.newArrayList());
	}

	private List<String> getParentCategory(List<String> categoryList, String categoryId) {
		BasMaterialCategory category = this.categoryService.getById(categoryId);
		String pid = category.getPid();
		if(StringUtils.isNotBlank(pid) && !StringUtils.equals("0",pid)) {
			categoryList.add(pid);
			categoryList = getParentCategory(categoryList, pid);
		}
		return categoryList;
	}

	@Override
	@Transactional
	public Result<?> delMaterial(ScanIO scanIo) {
		String list = scanIo.getList();
		if(StringUtils.isBlank(list)) {
			return Result.error("请扫描物料编码");
		}
		JSONArray jList = JSON.parseArray(list);
		List<String> codes = Lists.newArrayList();
		for (int i = 0; i < jList.size(); i++) {
			JSONObject jsonObject = jList.getJSONObject(i);
			codes.add(jsonObject.getString("code"));
		}
		List<BasMaterial> materials = this.materialService.getByCodes(codes);
		if(CollUtil.isEmpty(materials)) {
			return Result.error("库中不存在传入的物料");
		}
		List<String> materialIds = CollUtil.newArrayList();
		for (BasMaterial basMaterial : materials) {
			materialIds.add(basMaterial.getId());
		}
		boolean flag = this.materialService.removeByIds(materialIds);
		if(flag) {
			scanMapper.delNotMaterialIoBillEntry();
			scanMapper.delNotMaterialInventory();
			return Result.ok("删除成功。");
		}
		
		return Result.error("删除失败。");
	}

	@Override
	public Result<?> trayTake(ScanIO scanIo) {
		String trayCode = scanIo.getCode();
		if(StringUtils.isBlank(trayCode)) {
			return Result.error("未传入托盘码");
		}
		StkTray tray = trayService.lambdaQuery().eq(StkTray::getCode, trayCode).one();
		if(null == tray) {
			return Result.error("未查到相关托盘");
		}
		if(tray.getIsUse() == null || tray.getIsUse() == 0) {
			tray.setIsUse(1);
		}
		String listStr = scanIo.getList();
		if(StringUtils.isBlank(listStr)) {
			return Result.error("未传入物料信息");
		}
		JSONArray array = JSON.parseArray(listStr);
		if(array == null || array.size() == 0) {
			return Result.error("未传入物料信息");
		}
		List<String> codes = CollUtil.newArrayList();
		for(int i = 0; i < array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			String code = jsonObject.getString("code");
			codes.add(code);
		}
		List<String> materialIds = CollUtil.newArrayList();
		String customerId = tray.getCustomerId();
		if(customerId == null || StringUtils.isBlank(customerId)) {
			return Result.error("该托盘未关联客户，请重新打码");
		}
		List<StkTrayDetail> detailList = CollUtil.newArrayList();
		for (String code : codes) {
			BasMaterial material = this.materialService.getMaterialByCode(code);
			if(null == material) {
				material = this.materialTempService.tempToMaterial(code);
				if(material == null) {
					return Result.error(new StringBuffer("").append("编码为").append(code).append("的物料未找到，请核对后再提交").toString());
				}
			}
			String custId = material.getCustomerId();
			if(!customerId.equals(custId)) {
				return Result.error(new StringBuffer("").append("编码为").append(code).append("的物料客户与托盘客户不符").toString());
			}
			
			int count = this.trayDetailService.lambdaQuery().eq(StkTrayDetail::getTrayId, tray.getId()).eq(StkTrayDetail::getMaterialId, material.getId()).count();
			if(0 == count) {
				StkTrayDetail detail = new StkTrayDetail();
				detail.setTrayCode(tray.getCode());
				detail.setTrayId(tray.getId());
				detail.setMaterialCode(code);
				detail.setMaterialId(material.getId());
				detailList.add(detail);
				materialIds.add(material.getId());
			}
		}
		trayService.updateById(tray);
		boolean flag = trayDetailService.saveBatch(detailList);
		if(flag) {
			trayDetailService.lambdaUpdate().ne(StkTrayDetail::getTrayId, tray.getId())
			.in(StkTrayDetail::getMaterialId, materialIds).remove();
		}
		return Result.ok("操作成功");
	}

	@Override
	public Result<?> trayTakeOff(ScanIO scanIo) {
		String code = scanIo.getCode();
		if(StringUtils.isBlank(code)) {
			return Result.error("请传入物料编码");
		}
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到相关物料");
		}
		List<StkTrayDetail> list = this.trayDetailService.lambdaQuery().eq(StkTrayDetail::getMaterialId, material.getId()).list();
		if(!CollUtil.isEmpty(list)) {
			this.trayDetailService.lambdaUpdate().eq(StkTrayDetail::getMaterialId, material.getId()).remove();
		}
		return Result.ok("操作成功");
	}

	@Override
	public Result<?> getMaterialTray(ScanIO scanIo) {
		String code = scanIo.getCode();
		if(StringUtils.isBlank(code)) {
			return Result.error("未传入物料编码");
		}
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到编码对应的物料");
		}
		List<StkTrayDetail> list = this.trayDetailService.lambdaQuery().eq(StkTrayDetail::getMaterialId, material.getId()).orderByDesc(StkTrayDetail::getCreateTime).list();
		if(CollUtil.isEmpty(list)) {
			return Result.error("未找到该物料的上托记录");
		}
		StkTrayDetail detail = list.get(0);
		
		TrayVO vo = new TrayVO();
		vo.setTrayCode(detail.getTrayCode());
		vo.setTrayId(detail.getTrayId());
		return Result.ok(vo);
	}

	@Override
	public Result<?> getGlueMes(Integer inOutType) {
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		//入库
		if(1 == inOutType) {
			query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newArrayList("3","4", "5", "6"));
			query.isNull(ZrkQzOrder::getParentId);
		}
		//出库
		if(2 == inOutType) {
			query.in(ZrkQzOrder::getMesOrderStatus, CollUtil.newArrayList("3", "2", "1", "6"));
			query.isNull(ZrkQzOrder::getParentId);
		}
		ZzDeviceType deviceType = this.deviceTypeService.getGlueDeviceType();
		query.eq(ZrkQzOrder::getProcessId, deviceType.getId());
		query.orderByDesc(ZrkQzOrder::getCreateTime);
		query.last(" limit 200 ");
		List<ZrkQzOrder> list = this.mesService.list(query);
		return Result.ok(list);
	}
	
	@Override
	public Result<?> batchAddGlue(ScanIO scanIo) {
		Integer batchNum = scanIo.getBatchNum();
		if(null == batchNum || 0 == batchNum.intValue()) {
			return Result.error("请传入打印数量。");
		}
		String unitId = scanIo.getUnit();
		String number = scanIo.getNumber();
		if(StringUtils.isBlank(number)) {
			return Result.error("请填写数量。");
		}
		if(StringUtils.isBlank(unitId)) {
			return Result.error("请填写单位。");
		}
		String categoryId = scanIo.getCategoryId();
		if(StringUtils.isBlank(categoryId)) {
			return Result.error("请选择分类。");
		}
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(null == unit) {
			return Result.error("请选择分类。");
		}
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return Result.error("未找到物料分类。");
		}
		BigDecimal cost = scanIo.getAmount();
		if(null == cost) {
			return Result.error("未传入成本。");
		}
		String inspector = scanIo.getInspector();
		if(StringUtils.isBlank(inspector)) {
			return Result.error("未传入检验员。");
		}
		String topCode = category.getCode();
		Date date = DateUtils.getDate();
		BigDecimal numberDecimal = new BigDecimal(number);
		List<BasMaterialTemp> addList = Lists.newArrayList();
		String orderId = scanIo.getOrderNum();
		ZrkQzOrder qzOrder = this.mesService.getById(orderId);
		if(null == qzOrder) {
			return Result.error("未找到该MES单。");
		}
		//获得制胶工序
		ZzDeviceType deviceType = this.deviceTypeService.getGlueDeviceType();
		String procedureId = null;
		if(null != deviceType) {
			procedureId = deviceType.getId();
		}
		if(StringUtils.isBlank(procedureId)) {
			return Result.error("未找到制胶工序。");
		}
		String machineId = qzOrder.getMachineId();
		String machineName = StringUtils.EMPTY;
		ZzDevice device = this.deviceService.getById(machineId);
		if(null != device) {
			machineName = device.getDeviceName();
		}
		for (int i = 0; i < batchNum; i++) {
			String code = this.materialService.getCode(topCode);
			BasMaterialTemp material = new BasMaterialTemp();
			material.setCode(code);
			material.setCategoryId(categoryId);
			material.setName(category.getName());
			material.setMachine(machineId);
			material.setInspector(inspector);

			material.setUnitId(unit.getId());
			material.setSupplierId(category.getSupplierId());
			material.setAmount(numberDecimal);
			material.setProcedureId(orderId);
			material.setCost(cost);
			//获取物料相关宽度属性
			material.setModel(category.getName());
			material.setCreateTime(date);
			addList.add(material);
		}
		if(addList.size() > 0) {
			Result<Object> result = new Result<Object>();
			boolean isSuccess = this.materialTempService.saveBatch(addList);
			if(isSuccess) {
				List<Map<String, String>> resultList = Lists.newArrayList();
				Iterator<BasMaterialTemp> it = addList.iterator();
				String unitName = "";
//				BasMeasureUnit unit = this.unitService.getById(category.getUnitId());
				if(null != unit) {
					unitName = unit.getName();
				}
				String now = DateUtils.formatDate();
				while(it.hasNext()) {
					BasMaterialTemp material = it.next();
					String returnModel = material.getModel();
					Map<String, String> map = Maps.newHashMap();
					map.put("code", material.getCode());
					map.put("name", material.getName());
					map.put("model", returnModel);
					map.put("unit", unitName);
					BigDecimal amount = material.getAmount();
					if(null == number) {
						map.put("number", "");
					} else {
						map.put("number", amount.toString());
					}

					map.put("date", now);
					map.put("machine", machineName);
					
					resultList.add(map);
				}
				result.setResult(resultList);
				return result.success("操作成功");
			}
		}
		return null;
	}

	@Override
	public Result<?> categoryUnit(String categoryId) {
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(category == null) {
			return Result.error("选中的物料分类错误");
		}
		String unitId = category.getUnitId();
		if(StringUtils.isBlank(unitId)) {
			return Result.error("选中的物料分类没有维护单位。");
		}
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(null == unit) {
			return Result.error("选中的物料分类没有维护单位。");
		}
		return Result.ok(unit);
	}

	@Override
	public Result<JSONObject> glueOut(ScanIO scanIo, Result<JSONObject> result) {
		String mesId = scanIo.getOrderNum();
		if(StringUtils.isBlank(mesId)) {
			return result.error500("请选择MES单。");
		}
		//查询MES单据
		ZrkQzOrder mes = this.mesService.getById(mesId);
		if(mes == null) {
			return result.error500("请选择MES单。");
		}
		//查询物料
		String listStr = scanIo.getList();
		if(StringUtils.isBlank(listStr)) {
			return result.error500("请扫描物料编码。");
		}
		List<String> codes = Lists.newArrayList();
		JSONArray array = JSONArray.parseArray(listStr);
		if(null == array || 0 == array.size()) {
			return result.error500("请扫描物料编码。");
		}
		for (int i=0; i < array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			codes.add(jsonObject.getString("code"));
		}
		List<BasMaterial> materials = materialService.getByCodes(codes);
		if(CollUtil.isEmpty(materials)) {
			return result.error500("未找到相关物料。");
		}
		
		String prodId = mes.getId();
		if(StringUtils.isNotBlank(mes.getParentId())) {
			prodId = mes.getParentId();
		}
		
		//判断是否重复出库
		String operType = scanIo.getOperType();
		boolean inFlag = false;
		boolean outFlag = false;
		for (String string : ScanServiceImpl.inTypes) {
			if (operType.equals(string)) {
				inFlag = true;
				break;
			}
		}
		for (String string : ScanServiceImpl.outTypes) {
			if (operType.equals(string)) {
				outFlag = true;
				break;
			}
		}
		
		//验证提货单与扫码物料是否一致
		List<StkPickUpEntry> pickUpEntrys = scanMapper.getPickUpEntryByMes(prodId);
		List<String> pickUpCategoryIds = Lists.newArrayList();
		List<String> pickUpMaterialIds = Lists.newArrayList();
		if(CollUtil.isNotEmpty(pickUpEntrys)) {
			for(Iterator<StkPickUpEntry> iterator = pickUpEntrys.iterator(); iterator.hasNext();) {
				StkPickUpEntry entry = iterator.next();
				String categoryId = entry.getCategoryId();
				String materialId = entry.getMaterialId();
				if(StringUtils.isNotBlank(categoryId)) {
					pickUpCategoryIds.add(categoryId);
				}
				if(StringUtils.isNotBlank(materialId)) {
					pickUpMaterialIds.add(materialId);
				}
			}
		}
		//验证提货单与扫码物料是否一致
		for(Iterator<BasMaterial> iterator = materials.iterator(); iterator.hasNext();) {
			BasMaterial material = iterator.next();
			String code = material.getCode();
			StkIoBill latestBill = this.billMapper.selectByMaterialCode(code);
			if (null != latestBill) {
				String type = latestBill.getStockIoType();
				if (operType.equals(type)) {
					return result.error500(new StringBuffer("编码为").append(code).append("的物料已出库，不能重复操作").toString());
				}
				boolean inF = false;
				boolean outF = false;
				for (String string : ScanServiceImpl.inTypes) {
					if (type.equals(string)) {
						inF = true;
						break;
					}
				}
				for (String string : ScanServiceImpl.outTypes) {
					if (type.equals(string)) {
						outF = true;
						break;
					}
				}
				if ((inFlag && inF) || (outFlag && outF)) {
					return result.error500(new StringBuffer("编码为").append(code).append("的物料已出库，不能重复操作").toString());
				}
			}
			String categoryId = material.getCategoryId();
			if(StringUtils.isNotBlank(categoryId) && !pickUpCategoryIds.contains(categoryId)) {
				String materialId = material.getId();
				if(!pickUpMaterialIds.contains(materialId)) {
					return result.error500(new StringBuffer("编号为").append(material.getCode()).append("的物料与提货单不符").toString());
				}
			}
		}
		
		ZrkQzOrder preMes = this.mesService.getById(prodId);
		Date date = DateUtils.gettimestamp();
		
		String billNo = this.baseApi.getNoByCode("stock_io_bill_no");
		String stockIoType = scanIo.getOperType();
		String userName = scanIo.getUserName();
		StkIoBill bill = new StkIoBill();
		bill.setBillNo(billNo);
		bill.setStockIoType(stockIoType);
		bill.setBillDate(date);
		bill.setIsAuto(1);
		bill.setHasRp(0);
		bill.setClerkId(userName);
		bill.setHandlerId(userName);
		bill.setIsApproved(1);
		bill.setCreateBy(userName);
		bill.setCreateTime(date);
		bill.setIsRubric(0);
		bill.setIsClosed(0);
		bill.setBillProcStatus(ScanServiceImpl.BILL_STATUS_APPROVAL);
		bill.setSysOrgCode(scanIo.getOrgCode());
		bill.setRemark("制胶扫码出库");
		bill.setSourceType(ScanServiceImpl.PRODUCTION_SOURCE_TYPE);
		bill.setSourceId(preMes.getId());
		bill.setSourceNo(preMes.getCode());
		
		int entryNum = 1;
		List<StkIoBillEntry> entryList = Lists.newLinkedList();
		Map<String, BasMaterial> materialMap = Maps.newHashMap();
		for (BasMaterial material : materials) {
			materialMap.put(material.getId(), material);
			bill.setSupplierId(material.getSupplier());
			//查看当前物料的实时库存
			List<StkInventory> inventorys = this.inventoryService.lambdaQuery()
					.eq(StkInventory::getMaterialId, material.getId())
					.gt(StkInventory::getQty, BigDecimal.ZERO).list();
			if(CollUtil.isEmpty(inventorys)) {
				return result.error500(new StringBuffer("编码为").append(material.getCode()).append("的物料库存不足。").toString());
			}
			StkInventory inventory = inventorys.get(0);
			String warehouseId = inventory.getWarehouseId();
			//取出物料最近的出入库单
			List<StkIoBill> ioBillList = this.billMapper.getIoBillByMaterial(material.getId());
			StkIoBill bill1 = ioBillList.get(0);
			//获取之前的入库信息
			LambdaQueryWrapper<StkIoBillEntry> entryQuery = new LambdaQueryWrapper<>();
			entryQuery.eq(StkIoBillEntry::getMid, bill1.getId());
			entryQuery.eq(StkIoBillEntry::getMaterialId, material.getId());
			List<StkIoBillEntry> inEntrys = this.billEntryService.list(entryQuery);
			StkIoBillEntry inEntry = inEntrys.get(0);
			//判断库存中的物料
			BigDecimal checkNumber = inEntry.getQty();
			String batchNo = inEntry.getBatchNo();
			BigDecimal cost = inEntry.getCost();
			StkIoBillEntry billEntry = new StkIoBillEntry();
			billEntry.setMaterialId(material.getId());
			billEntry.setBillNo(billNo);
			billEntry.setMid(bill.getId());
			billEntry.setBatchNo(batchNo);
			billEntry.setQty(checkNumber);
			billEntry.setSourceType(ScanServiceImpl.PROCESSING_ORDER_ENTRY_TYPE + bill1.getStockIoType());
			billEntry.setSourceEntryId(inEntry.getId());
			billEntry.setUnitId(material.getUnitId());
			billEntry.setWarehouseId(warehouseId);
			billEntry.setSettleQty(checkNumber);
			billEntry.setInventoryQty(checkNumber);
			billEntry.setWidth(material.getWidth());
			billEntry.setLength(material.getLength());
			billEntry.setSourceEntryNo(batchNo);
//			billEntry.setCost(inEntry.getCost());
			billEntry.setInventoryUnitId(inEntry.getUnitId());
			billEntry.setEntryNo(entryNum);
			billEntry.setCost(cost);
			entryList.add(billEntry);
			entryNum ++;
		}
		this.billService.saveMain(bill, entryList);
		this.billService.updateInventory(bill, entryList);
		for (StkIoBillEntry stkIoBillEntry : entryList) {
			BasMaterial material = materialMap.get(stkIoBillEntry.getMaterialId());
			logService.insertLog(bill.getId(), date, stkIoBillEntry.getId(), bill.getStockIoType(), 0, material, stkIoBillEntry.getUnitId(), mes.getId(), 2, stkIoBillEntry.getCost(), stkIoBillEntry.getQty(), prodId);
		}
		
		//检测是否出库完成
		System.out.println("制胶出库完成");
		return result.success("制胶出库完成");
	}

	@Override
	public Result<?> printSalOut(ScanIO scanIo) {
		//查询销售订单
		String orderNum = scanIo.getOrderNum();
		ZrkShoporder order = zrkShopOrderService.getById(orderNum);
		if(null == order) {
			return Result.error("系统中未找到相关销售订单");
		}
		List<StkIoBill> list = billService.lambdaQuery().eq(StkIoBill::getSourceId, order.getId()).list();
		if(CollUtil.isEmpty(list)) {
			String orderNo = order.getOrderNo();
			list = billService.lambdaQuery().eq(StkIoBill::getSourceNo, orderNo).list();
			if(CollUtil.isEmpty(list)) {
				return Result.error("未找到相关销售订单的出入库记录");
			}
		}
		StkIoBill bill = list.get(0);
		this.inventoryService.upDdFile(bill.getId());
		return Result.ok();
	}

	@Override
	public Result<?> getOrderSaleOutInfo(String orderId) {
		ZrkShoporder zrkShoporder = this.zrkShopOrderService.getById(orderId);
		if(null == zrkShoporder) {
			return Result.error("未找到销售订单");
		}
		List<ZrkOrderProduct> productList = this.productService.selectByMainId(zrkShoporder.getId());
		Map<String, Object> result = Maps.newHashMap();
		result.put("orderInfo", productList);
		List<StkIoBill> billList = billService.lambdaQuery().eq(StkIoBill::getSourceNo, zrkShoporder.getOrderNo()).list();
		if(CollUtil.isEmpty(billList)) {
			result.put("outInfo", new ArrayList<SaleOutVO>());
		} else {
			List<String> billIds = Lists.newArrayList();
			for (StkIoBill bill : billList) {
				billIds.add(bill.getId());
			}
			List<StkIoBillEntry> entrys = billEntryService.lambdaQuery().in(StkIoBillEntry::getMid, billIds).list();
			List<SaleOutVO> list = Lists.newArrayList();
			if(CollUtil.isNotEmpty(entrys)) {
				List<String> materialIds = Lists.newArrayList(); 
				for (StkIoBillEntry entry : entrys) {
					String materialId = entry.getMaterialId();
					materialIds.add(materialId);
				}
				List<BasMaterial> materials = this.materialService.lambdaQuery().in(BasMaterial::getId, materialIds).list();
				Map<SaleOutVO, SaleOutVO> map = Maps.newHashMap();
				if(CollUtil.isNotEmpty(materials)) {
					for (BasMaterial material : materials) {
						SaleOutVO keVo = new SaleOutVO();
						keVo.setCategoryId(material.getCategoryId());
						keVo.setModel(material.getModel());
						SaleOutVO saleOutVO = map.get(keVo);
						if(null == saleOutVO) {
							saleOutVO = new SaleOutVO();
							saleOutVO.setCategoryId(material.getCategoryId());
							saleOutVO.setMaterialName(material.getName());
							saleOutVO.setModel(material.getModel());
							BigDecimal viceQuantity = material.getViceQuantity();
							if(null == viceQuantity) {
								viceQuantity = BigDecimal.ONE;
							}
							saleOutVO.setCount(viceQuantity);
							map.put(keVo, saleOutVO);
						} else {
							BigDecimal viceQuantity = material.getViceQuantity();
							if(null == viceQuantity) {
								viceQuantity = BigDecimal.ONE;
							}
							BigDecimal count = saleOutVO.getCount();
							count = count.add(viceQuantity);
							saleOutVO.setCount(count);
						}
					}
				}
				for (SaleOutVO key : map.keySet()) {
					SaleOutVO saleOutVO = map.get(key);
					if(null != saleOutVO) {
						list.add(saleOutVO);
					}
				}
			}
			result.put("outInfo", list);
		}
		
		return Result.ok(result);
	}
	
	@Override
	public Result<?> getCustomerOrderSaleOutInfo(String customerId) {
//		List<ZrkShoporder> orderList = this.zrkShopOrderService
//				.lambdaQuery().eq(ZrkShoporder::getCustomerId, customerId).in(ZrkShoporder::getOrderStatus, Sets.newHashSet("1", "2")).list();
//		if(CollUtil.isEmpty(orderList)) {
//			return Result.error("未找到销售订单");
//		}
//		List<String> idList = Lists.newArrayList();
//		for (ZrkShoporder order : orderList) {
//			idList.add(order.getId());
//		}
		List<ZrkOrderProduct> productList = this.productService.getCustomerNotOutCompleteProduct(customerId);
		if(CollUtil.isEmpty(productList)) {
			return Result.error("未找到销售订单");
		}
		if(CollUtil.isNotEmpty(productList)) {
			for (ZrkOrderProduct product : productList) {
				BigDecimal outCount = product.getOutCount() == null ? BigDecimal.ZERO : product.getOutCount();
				BigDecimal productCount = product.getProductCount();
				BigDecimal leftCount = productCount.subtract(outCount);
				product.setProductCount(leftCount);
			}
		}
		Map<String, Object> result = Maps.newHashMap();
		result.put("orderInfo", productList);
		result.put("outInfo", productList);
		return Result.ok(result);
	}

	@Override
	@Transactional
	public Result<?> processingOut(ScanIO scan) {
		// TODO Auto-generated method stub
		String listStr = scan.getList();
		if(StringUtils.isBlank(listStr)) {
			return Result.error("未传入物料信息");
		}
		JSONArray array = JSON.parseArray(listStr);
		if(array == null || array.size() == 0) {
			return Result.error("未传入物料信息");
		}
		List<String> codeList = Lists.newArrayList();
		for(int i = 0; i < array.size(); i ++) {
			JSONObject jsonObject = array.getJSONObject(i);
			String code = jsonObject.getString("code");
			if(StringUtils.isNotBlank(code)) {
				codeList.add(code);
			}
		}
		if(CollUtil.isEmpty(codeList)) {
			return Result.error("未传入物料信息");
		}
		List<BasMaterial> materials = Lists.newArrayList();
		List<String> sigleMaterailCodeList = Lists.newArrayList();
		for (String code : codeList) {
			if(ScanUtil.isTrayCode(code)){
				StkTray tray = this.trayService.getTrayByCode(code);
				if(null == tray) {
					continue;
				}
				String trayId = tray.getId();
				List<StkTrayDetail> details = this.trayDetailService.selectByMainId(trayId);
				if(CollUtil.isEmpty(details)) {
					continue;
				}
				List<String> codes = Lists.newArrayList();
				for(StkTrayDetail detail : details) {
					String materialCode = detail.getMaterialCode();
					codes.add(materialCode);
				}
				if(CollUtil.isEmpty(codes)) {
					continue;
				}
				List<BasMaterial> materialList = this.materialService.getByCodes(codes);
				materials.addAll(materialList);
			} else {
				sigleMaterailCodeList.add(code);
			}
		}
		if(!sigleMaterailCodeList.isEmpty()) {
			List<BasMaterial> materialList = this.materialService.getByCodes(sigleMaterailCodeList);
			if(null != materialList) {
				materials.addAll(materialList);
			}
		}
		
		if(CollUtil.isEmpty(materials)) {
			return Result.error("未查询到扫码的物料");
		}
		List<String> materialIds = Lists.newArrayList();
		for (BasMaterial material : materials) {
			materialIds.add(material.getId());
		}
		int count = inventoryService.countHasInventoryMateiral(materialIds);
		if(0 < count) {
			return Result.error("有的物料库存不足");
		}
		String orderNum = scan.getOrderNum();
		if(StringUtils.isBlank(orderNum)) {
			return Result.error("请选择代加工单");
		}
		StkProcessingOrder processingOrder = this.processingService.getById(orderNum);
		if(null == processingOrder) {
			return Result.error("未找到代加工单");
		}
		String orderId = processingOrder.getId();
		List<StkProcessingRecord> recordList = processingRecordService.selectByMainId(orderId);
		if(CollUtil.isEmpty(recordList)) {
			return Result.error("代加工单的详情未找到，请先核对该代加工单信息");
		}
		List<String> recordCategoryIdList = Lists.newArrayList();
		for (StkProcessingRecord record : recordList) {
			String outCategoryId = record.getOutCategoryId();
			recordCategoryIdList.add(outCategoryId);
		}
		
		//封装信息
		String userName = scan.getUserName();
		String orgCode = scan.getOrgCode();
		StkIoBill bill = new StkIoBill();
		Date now = DateUtil.date();
		String billNo = this.baseApi.getNoByCode("stock_io_bill_no");
		bill.setBillNo(billNo);
		bill.setBillDate(now);
		bill.setSourceId(orderNum);
		bill.setSourceNo(processingOrder.getOrderNo());
		bill.setStockIoType("3995");
		bill.setCreateTime(now);
		bill.setBillProcStatus(BILL_SUBMIT_STATUS);
		bill.setHandlerId(userName);
		bill.setHasRp(0);
		bill.setIsRubric(0);
		bill.setIsSameSettle(0);
		bill.setSysOrgCode(orgCode);
		List<StkIoBillEntry> entrys = Lists.newLinkedList();
		int entryNo = 10;
		Iterator<BasMaterial> iterator = materials.iterator();
		while(iterator.hasNext()) {
			BasMaterial material = iterator.next();
			String materialId = material.getId();
			String categoryId = material.getCategoryId();
			if(!recordCategoryIdList.contains(categoryId)) {
				return Result.error("物料编码为" + material.getCode() + "的物料与代加工单中要出库的物料不符。");
			}
			StkInventory inventory = inventoryService.getByMaterial(materialId);
			if(inventory == null) {
				continue;
			}
			StkIoBillEntry entry = new StkIoBillEntry();
			entry.setInWarehouseId(WarehouseConstant.DJG_ID);
			entry.setMaterialId(materialId);
			entry.setUnitId(material.getUnitId());
			entry.setInventoryUnitId(material.getUnitId());
			entry.setBatchNo(inventory.getBatchNo());
			entry.setEntryNo(entryNo);
			entry.setBillNo(billNo);
			entry.setInventoryCost(inventory.getCost());
			entry.setInventoryQty(inventory.getQty());
			entry.setQty(inventory.getQty());
			entry.setCost(inventory.getCost());
			entry.setWarehouseId(inventory.getWarehouseId());
			entry.setSupplierId(inventory.getSupplierId());
			entrys.add(entry);
			entryNo = entryNo + 10;
		}
		if(entrys.size() == 0) {
			return Result.error("物料编码与实时库存不匹配。");
		}
		billService.saveMain(bill, entrys);
		billService.approve(bill.getId());
		
		String isFinal = scan.getIsFinal();
		if("是".equals(isFinal)) {
			processingOrder.setOrderStatus("3");
		} else {
			processingOrder.setOrderStatus("2");
		}
		this.processingService.updateById(processingOrder);
		log.info("代加工出库完成" + bill.getBillNo());
		return Result.ok("代加工出库完成");
	}

	@Override
	public Result<?> processingPrint(ScanIO scan) {
		// TODO Auto-generated method stub
		String categoryId = scan.getCategoryId();
		if(StringUtils.isBlank(categoryId)) {
			return Result.error("请选择物料分类");
		}
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return Result.error("未找到该物料分类");
		}
		Integer batchNum = scan.getBatchNum();
		if(null == batchNum) {
			return Result.error("请填写打印数量");
		}
		String orderNum = scan.getOrderNum();
		if(StringUtils.isBlank(orderNum)) {
			return Result.error("请选择代加工单");
		}
		StkProcessingOrder processingOrder = this.processingService.getById(orderNum);
		if(null == processingOrder) {
			return Result.error("未找到代加工单");
		}
		String categoryCode = category.getCode();
		List<BasMaterialTemp> temps = Lists.newArrayList();
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String unitId = category.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(null == unit) {
			return Result.error("请维护物料分类的单位");
		}
		String unitName = unit.getName();
		String numberStr = scan.getNumber();
		if(StringUtils.isBlank(numberStr)) {
			return Result.error("请填写数量");
		}
		BigDecimal decimal = new BigDecimal(numberStr);
		String model = scan.getModel();
		if(StringUtils.isBlank(model)) {
			return Result.error("请填写规格");
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String workNo = StringUtils.EMPTY;
		if(sysUser != null) {
			workNo = sysUser.getWorkNo();
		}
		for(int i = 0; i < batchNum; i++) {
			String materialCode = this.materialService.getCode(categoryCode);
			BasMaterialTemp temp = new BasMaterialTemp();
			temp.setCategoryId(categoryId);
			temp.setName(category.getName());
			temp.setCode(materialCode);
			temp.setWidth(width);
			temp.setLength(length);
			temp.setUnitId(category.getUnitId());
			temp.setSupplierId(processingOrder.getSupplierId());
			temp.setCreateTime(new Date());
			temp.setProcessingId(processingOrder.getId());
			temp.setModel(model);
			temp.setInspector(workNo);
			
			if("平方".equals(unitName)) {
				temp.setAmount(decimal);
				temp.setSquare(decimal);
			} else {
				temp.setAmount(decimal);
			}
			
			temps.add(temp);
		}
		boolean bl = this.materialTempService.saveBatch(temps);
		String inDate = DateUtils.formatDate();
		if(bl) {
			List<JSONObject> resultList = Lists.newArrayList();
			for (BasMaterialTemp temp : temps) {
				JSONObject obj = new JSONObject();
				obj.put("name", temp.getName());
				obj.put("model", temp.getModel());
				obj.put("unit", unitName);
				obj.put("code", temp.getCode());
				obj.put("workNo", workNo);
				obj.put("time", inDate);
				obj.put("number", temp.getAmount());
				
				resultList.add(obj);
			}
			
			return Result.ok(resultList);
		} else {
			return Result.error("操作失败");
		}
	}

	@Override
	public Result<?> initMaterial(String code) {
		// TODO Auto-generated method stub
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		Map<String, Object> result = Maps.newHashMap();
		result.put("code", temp.getCode());
		result.put("length", temp.getLength());
		result.put("width", temp.getWidth());
		result.put("model", temp.getModel());
		String unitId = temp.getUnitId();
		result.put("unitId", unitId);
		BasMeasureUnit unit = unitService.getById(unitId);
		if(null != unit) {
			result.put("unitName", unit.getName());
		}
		String customerId = temp.getCustomerId();
		if(StringUtils.isNotBlank(customerId)) {
			result.put("customerId", customerId);
			BasCustomer customer = this.customerMapper.selectById(customerId);
			if(null != customer) {
				String customerName = customer.getName();
				result.put("customerName", customerName);
			}
		}
		BigDecimal pageNum = temp.getPageNum();
		if(null == pageNum) {
			result.put("pageNum", StringUtils.EMPTY);
		} else {
			result.put("pageNum", pageNum.toString());
		}
		
		return Result.ok(result);
	}

	@Override
	public Result<?> getAllCustomer() {
		LambdaQueryWrapper<BasCustomer> query = new LambdaQueryWrapper<>();
		query.eq(BasCustomer::getIsEnabled, 1);
		query.orderByAsc(BasCustomer::getName);
		List<BasCustomer> list = this.customerMapper.selectList(query);
		return Result.ok(ScanUtil.changeListToVector(list));
	}

	@Override
	public Result<?> rePrint(ScanIO scan) {
		String code = scan.getCode();
		if(StringUtils.isBlank(code)) {
			return Result.error("请扫码。");
		}
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到相关物料。");
		}
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == temp) {
			return Result.error("未找到相关物料。");
		}
		String procedureId = temp.getProcedureId();
		if(StringUtils.isBlank(procedureId)) {
			return Result.error("未找到MES单信息，请确认是否是生产的物料。");
		}
		ZrkQzOrder mes = this.mesService.getById(procedureId);
		if(null == mes) {
			return Result.error("未找到MES单信息，请确认是否是生产的物料。");
		}
		String processId = mes.getProcessId();
		if(StringUtils.isBlank(processId)) {
			return Result.error("未找到该物料的生产工序");
		}
		ZzDeviceType deviceType = this.deviceTypeService.getById(processId);
		String processName = deviceType.getDeviceTpyeName();
		//判断是复合、分切还是切张
		boolean fqFlag = false;
		boolean qzFlag = false;
		boolean fhFlag = false;
		if(processName.contains("分切")) {
			fqFlag = true;
		}
		else if(processName.contains("切张")) {
			qzFlag = true;
		}
		else if(processName.contains("复合")) {
			fhFlag = true;
		}
		
		//获取操作人员
		String userIds = mes.getOperatorUsers();
		String[] userIdArray = StringUtils.split(userIds, ",");
		List<String> workNoList = CollUtil.newLinkedList();
		for (int i = 0; i < userIdArray.length; i++) {
			String userId = userIdArray[i];
			List<ErpSysUser> users = this.userMapper.getUser(userId);
			ErpSysUser user = null;
			if(CollUtil.isEmpty(users)) {
				user = this.userMapper.getUserByUserName(userId);
			} else {
				user = users.get(0);
			}
			workNoList.add(user.getWorkNo());
		}
		String workNo = CollUtil.join(workNoList, ",");
		
		//更新物料信息
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String model = scan.getModel();
		String pageNumStr = scan.getNumber();
		String customerId = scan.getCustomerId();
		if(StringUtils.isNotBlank(customerId)) {
			material.setCustomerId(customerId);
			temp.setCustomerId(customerId);
		}
		if(length != null) {
			material.setLength(length);
			temp.setLength(length);
		}
		if(width != null) {
			material.setWidth(width);
			temp.setWidth(width);
		}
		if(StringUtils.isNotBlank(model)) {
			material.setModel(model);
			temp.setModel(model);
		}
		if(fhFlag || fqFlag) {
			BigDecimal lengthDecimal = material.getLength();
			BigDecimal widthDecimal = material.getWidth();
			BigDecimal square = widthDecimal.divide(new BigDecimal("100"), 8, BigDecimal.ROUND_DOWN).multiply(lengthDecimal);
			material.setSquare(square);
			temp.setSquare(square);
			temp.setAmount(square);
		}else if(qzFlag) {
			if(StringUtils.isNotBlank(pageNumStr)) {
				BigDecimal pageNum = new BigDecimal(pageNumStr);
				temp.setPageNum(pageNum);
			}
			BigDecimal hunDecimal = new BigDecimal("100");
			BigDecimal pageNum =temp.getPageNum();
			BigDecimal lengthDecimal = material.getLength();
			BigDecimal widthDecimal = material.getWidth();
			BigDecimal square = lengthDecimal.divide(hunDecimal, 8, BigDecimal.ROUND_DOWN);
			square = square.multiply(widthDecimal.divide(hunDecimal, 8, BigDecimal.ROUND_DOWN));
			square = square.multiply(pageNum);
			material.setSquare(square);
			temp.setSquare(square);
			temp.setAmount(square);
		}
		this.materialService.updateById(material);
		this.materialTempService.updateById(temp);
		
		Map<String, String> resultMap = Maps.newHashMap();
		String formulaId = temp.getFormulaId();
		if(StringUtils.isNotBlank(formulaId)) {
			BasProductFormula formula = formulaService.getById(formulaId);
			if(null != formula) {
				String preMaterial = formula.getPfName();
				resultMap.put("preMaterial", preMaterial.trim());
			}
		}
		String dateStr = StringUtils.EMPTY;
		if(fhFlag) {
			dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "A";
			resultMap.put("glue", temp.getGluePosition());
			resultMap.put("processName", "复合");
		}
		if(fqFlag) {
			resultMap.put("processName", "分切");
			dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "B";
			String pid = temp.getPid();
			String[] strs = StringUtils.split(pid, ",");
			if(strs.length > 0) {
				pid = strs[0];
			}
			BasMaterial pMaterial = this.materialService.getById(pid);
			BasMaterialTemp pMaterialTemp = null;
			if(null != pMaterial) {
				Date preTime = pMaterial.getCreateTime();
				String preTimeString = ScanUtil.changeDateToString(preTime) + "A";
				resultMap.put("fhTime", preTimeString);
				String preCode = pMaterial.getCode();
				pMaterialTemp = this.materialTempService.getByCode(preCode);
				
			}
			
			String roll = temp.getRollDirect();
			if(roll == null) {
				roll = StringUtils.EMPTY;
			}
//			resultMap.put("preCode", code);
			resultMap.put("roll", roll);
			String machineId = StringUtils.EMPTY;
			if(null != pMaterialTemp) {
				resultMap.put("glue", pMaterialTemp.getGluePosition());
				resultMap.put("isPrint", pMaterialTemp.getIsPrint());
				machineId = pMaterialTemp.getMachine();
			} else {
				resultMap.put("glue", StringUtils.EMPTY);
				resultMap.put("isPrint", StringUtils.EMPTY);
			}
			
			Integer knifeNum = temp.getKnifeNum();
			resultMap.put("knife", null == knifeNum ? StringUtils.EMPTY : knifeNum.toString());
			
			if(StringUtils.isNotBlank(machineId)) {
				ZzDevice zzDevice = this.deviceService.getById(machineId);
				if(zzDevice != null) {
					resultMap.put("preMachine", zzDevice.getDeviceName());
				}
			}
		}
		
		Map<String, String> qzMap = Maps.newHashMap();
		if(qzFlag) {
			resultMap.put("processName", "切张");
			dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "C";
			String pid = temp.getPid();
			String[] strs = StringUtils.split(pid, ",");
			if(strs.length > 0) {
				pid = strs[0];
			}
			BasMaterial fqMaterial = this.materialService.getById(pid);
			if(null != fqMaterial) {
				Date preTime = fqMaterial.getCreateTime();
				String preTimeString = ScanUtil.changeDateToString(preTime) + "B";
				resultMap.put("fqTime", preTimeString);
				String fqCode = fqMaterial.getCode();
				BasMaterialTemp preTemp = this.materialTempService.getByCode(fqCode);
				String prePid = preTemp.getPid();
				if(StringUtils.isNotBlank(prePid)) {
					String[] preStrs = StringUtils.split(prePid, ",");
					if(preStrs.length > 0) {
						prePid = preStrs[0];
					}
				}
				if(preTemp != null) {
					qzMap.put("fqRoll", StringUtils.isBlank(preTemp.getRollDirect()) ? StringUtils.EMPTY : preTemp.getRollDirect());
					qzMap.put("fqKnife", preTemp.getKnifeNum() != null ? preTemp.getKnifeNum().toString() : StringUtils.EMPTY);
					qzMap.put("fqIn", StringUtils.isBlank(preTemp.getInspector()) ? StringUtils.EMPTY : preTemp.getInspector());
				}
				BasMaterial fhMaterial = this.materialService.getById(prePid);
				if(fhMaterial != null) {
					Date fhTime = fhMaterial.getCreateTime();
					String fhTimeStr = ScanUtil.changeDateToString(fhTime) + "A";
					resultMap.put("fhTime", fhTimeStr);
					String fhCode = fhMaterial.getCode();
					BasMaterialTemp fhTemp = this.materialTempService.getByCode(fhCode);
					if(null != fhTemp) {
						qzMap.put("fhRoll", StringUtils.isBlank(fhTemp.getRollDirect()) ? StringUtils.EMPTY : fhTemp.getRollDirect());
					}
				}
			}
			Integer knifeNum = temp.getKnifeNum();
			resultMap.put("knife", null == knifeNum ? StringUtils.EMPTY : knifeNum.toString());
			
			resultMap.put("fqRoll", null == qzMap.get("fqRoll") ? StringUtils.EMPTY : qzMap.get("fqRoll"));
			resultMap.put("fqKnife", null == qzMap.get("fqKnife") ? StringUtils.EMPTY : qzMap.get("fqKnife"));
			resultMap.put("fqIn", null == qzMap.get("fqIn") ? StringUtils.EMPTY : qzMap.get("fqIn"));
			resultMap.put("fhRoll", null == qzMap.get("fhRoll") ? StringUtils.EMPTY : qzMap.get("fhRoll"));
		}
		
		//需要打印的名称
		String categoryId = material.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		String printName = category.getName();
		String materialNo = category.getMaterialNo();
		if(StringUtils.isNotBlank(materialNo)) {
			printName = printName + " " + materialNo;
		}
		String unitId = material.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(unit != null) {
			resultMap.put("unit", unit.getName());
		} else {
			resultMap.put("unit", StringUtils.EMPTY);
		}
		resultMap.put("name", printName);
		resultMap.put("code", temp.getCode());
		resultMap.put("model", temp.getModel());
		resultMap.put("number", temp.getSquare().toString());
		resultMap.put("workNo", workNo);
		resultMap.put("paperNum", null == temp.getPageNum() ? StringUtils.EMPTY : temp.getPageNum().toString());
		resultMap.put("date", dateStr);
		//查询设备并判断
		String deviceId = mes.getMachineId();
		ZzDevice device = this.deviceService.getById(deviceId);
		String mathineName = "";
		if(null != device) {
			mathineName = device.getDeviceName();
		}
		resultMap.put("machine", mathineName);
		resultMap.put("remark", temp.getRemark());
		//传入客户
		BasCustomer customer = this.customerMapper.selectById(temp.getCustomerId());
		if(null != customer) {
			String customerName = customer.getName();
			customerName = StringUtils.replace(customerName, "\n", "");
			customerName = StringUtils.replace(customerName, "\r", "");
			resultMap.put("customer", customerName);
		} else {
			resultMap.put("customer", StringUtils.EMPTY);
		}
		String string = resultMap.get("preMaterial");
		if(StringUtils.isBlank(string) || "null".equals(string)) {
			resultMap.put("preMaterial", StringUtils.EMPTY);
		}
		return Result.ok(resultMap);
	}

	@Override
	public Result<?> scanMaterial(ScanIO scan) {
		// TODO Auto-generated method stub
		synchronized(Scan3rdServiceImpl.class) {
			//盘点单ID
			String orderNum = scan.getOrderNum();
			if(StringUtils.isBlank(orderNum)) {
				return Result.error("请选择盘点单");
			}
			String listStr = scan.getList();
			if(StringUtils.isBlank(listStr)) {
				return Result.error("请扫描物料编码");
			}
			JSONArray jList = JSON.parseArray(listStr);
			List<String> codes = Lists.newArrayList();
			for (int i = 0; i < jList.size(); i++) {
				JSONObject jsonObject = jList.getJSONObject(i);
				codes.add(jsonObject.getString("code"));
			}
			return materialLogService.addMaterialLog(codes, orderNum);
		}
	}

	@Override
	public Result<?> checkMesMaterial(ScanIO scan) {
		// TODO Auto-generated method stub
		String listStr = scan.getList();
		if(StringUtils.isBlank(listStr)) {
			return Result.error("请扫描物料编码");
		}
		JSONArray jList = JSON.parseArray(listStr);
		List<String> codes = Lists.newArrayList();
		for (int i = 0; i < jList.size(); i++) {
			JSONObject jsonObject = jList.getJSONObject(i);
			codes.add(jsonObject.getString("code"));
		}
		List<BasMaterial> materialList = this.materialService.getByCodes(codes);
		if(CollUtil.isEmpty(materialList)) {
			return Result.error("没有找到扫描的物料码对应的物料。");
		}
		
		String mesId = scan.getOrderNum();
		if(StringUtils.isBlank(mesId)) {
			return Result.error("未传入MES单号");
		}
		ZrkQzOrder mes = this.mesService.getById(mesId);
		if(null == mes) {
			return Result.error("未找到MES单");
		}
		String mesCode = mes.getCode();
		List<StkIoBill> billList = this.billService.lambdaQuery().eq(StkIoBill::getSourceNo, mesCode).orderByAsc(StkIoBill::getCreateTime).list();
		if(CollUtil.isEmpty(billList)) {
			return Result.error("MES单没有出入库记录");
		}
		List<String> billIds = Lists.newArrayList();
		for (StkIoBill bill : billList) {
			billIds.add(bill.getId());
		}
		List<StkIoBillEntry> entryList = this.billEntryService.lambdaQuery().in(StkIoBillEntry::getMid, billIds).orderByAsc(StkIoBillEntry::getId).list();
		if(CollUtil.isEmpty(entryList)) {
			return Result.error("未找到MES单的出入库记录");
		}
		Map<String, List<StkIoBillEntry>> materialEntryMap = Maps.newHashMap();
		List<String> materialIds = Lists.newArrayList();
		for (StkIoBillEntry entry : entryList) {
			String materialId = entry.getMaterialId();
			List<StkIoBillEntry> stkIoBillEntrys = materialEntryMap.get(materialId);
			if(stkIoBillEntrys == null) {
				materialEntryMap.put(entry.getMaterialId(), CollUtil.newArrayList(entry));
			} else {
				stkIoBillEntrys.add(entry);
			}
			if(!materialIds.contains(materialId)) {
				materialIds.add(materialId);
			}
		}
		Map<String, BasMaterial> materialMap = Maps.newHashMap();
		List<BasMaterial> unHaveList = Lists.newArrayList();
		List<BasMaterial> haveList = Lists.newArrayList();
		for(BasMaterial material : materialList) {
			String materialId = material.getId();
			materialMap.put(materialId, material);
			if (!materialIds.contains(materialId)) {
				unHaveList.add(material);
			} else {
				haveList.add(material);
			}
		}
		if(unHaveList.size() == 0) {
			return Result.ok("扫描的物料都是该MES单出库的物料");
		} else {
			List<String> codeList = Lists.newArrayList();
			for (BasMaterial basMaterial : unHaveList) {
				codeList.add(basMaterial.getCode());
			}
			String codeStr = CollUtil.join(codeList, ",");
			return Result.ok("编码为" + codeStr + "的物料不是该MES单出库的物料");
		}
	}

	@Override
	@GetMapping("/getCheckMes")
	public Result<?> getCheckMes(String procedureId) {
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		query.eq(ZrkQzOrder::getProcessId, procedureId);
		query.in(ZrkQzOrder::getMesOrderStatus, Lists.newArrayList("1", "2", "3"));
		query.orderByDesc(ZrkQzOrder::getCreateTime);
		query.last(" limit 200 ");
		List<ZrkQzOrder> list = this.mesService.list(query);
		list = ScanUtil.changeListToVector(list);
		return Result.ok(list);
	}

	@Override
	public Result<Map<String, Object>> rePrintPurchase(ScanIO scan) {
		// TODO Auto-generated method stub
		Result<Map<String, Object>> result = new Result<>();
		String code = scan.getCode();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			return result.error500("未找到相关物料");
		}
		String materialId = material.getId();
		Integer count = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).count();
		if(count <= 0) {
			return result.error500("物料库存不足");
		}
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == temp) {
			return result.error500("未找到相关物料");
		}
		BasMaterial purMaterial = this.materialService.getPurchaseMaterial(materialId);
		if(purMaterial == null) {
			return result.error500("该物料不是采购入库物料");
		}
		
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String model = scan.getModel();
		BigDecimal amount = scan.getAmount();
		String categoryId = scan.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		String unitId = scan.getUnit();
		material.setLength(length);
		material.setWidth(width);
		material.setModel(model);
		material.setQuantity(amount);
		material.setUnitId(unitId);
		material.setCategoryId(categoryId);
		if(null != category) {
			material.setName(category.getName());
		}
		this.materialService.updateById(material);
		if(null != temp) {
			temp.setAmount(amount);
			temp.setLength(length);
			temp.setWidth(width);
			temp.setCategoryId(categoryId);
			temp.setModel(model);
			temp.setUnitId(unitId);
			if(null != category) {
				temp.setName(category.getName());
			}
			this.materialTempService.updateById(temp);
		}
		List<StkInventory> list = inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, material.getId()).list();
		if(CollUtil.isNotEmpty(list)) {
			for (StkInventory inventory : list) {
				BigDecimal qty = inventory.getQty();
				if(qty.compareTo(BigDecimal.ZERO) > 0) {
					inventory.setQty(amount);
					inventory.setUnitId(unitId);
					this.inventoryService.updateById(inventory);
				}
			}
		}
		
		Map<String, Object> map = Maps.newHashMap();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(null != unit) {
			map.put("unitName", unit.getName());
		}
		map.put("model", material.getModel());
		map.put("time", DateUtil.formatDate(material.getCreateTime()));
		map.put("name", material.getName());
		map.put("num", amount);
		map.put("code", material.getCode());
		if(null != temp && StringUtils.isNotBlank(temp.getInspector())) {
			map.put("check", temp.getInspector());
		}
		result.setResult(map);
		result.setSuccess(Boolean.TRUE);
		result.setCode(CommonConstant.SC_OK_200);
		return result;
	}

	@Override
	public Result<Map<String, Object>> rePrintFh(ScanIO scan) {
		Result<Map<String, Object>> result = new Result<>();
		String code = scan.getCode();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == material || null == temp) {
			return result.error500("未找到相关物料");
		}
		String orderId = temp.getOrderId();
		if(StringUtils.isBlank(orderId)) {
			return result.error500("该物料不是复合入库物料");
		}
		ZrkQzOrder order = this.mesService.getById(orderId);
		if(null == order) {
			return result.error500("该物料不是复合入库物料");
		}
		//判断工序是否正确
		String processId = order.getProcessId();
		ZzDeviceType deviceType = this.deviceTypeService.getById(processId);
		String deviceTpyeName = deviceType.getDeviceTpyeName();
		if(!deviceTpyeName.contains("复合")) {
			return result.error500("该物料不是复合入库物料");
		}
		
		String materialId = material.getId();
		Integer count = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).count();
		if(count <= 0) {
			return result.error500("物料库存不足");
		}
		String categoryId = scan.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return result.error500("请选择物料分类");
		}
		String unitId = category.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		
		String customerId = scan.getCustomerId();
		BasCustomer customer = null;
		if(StringUtils.isNotBlank(customerId)) {
			customer = this.customerMapper.selectById(customerId);
		}
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String model = width.stripTrailingZeros().toPlainString() + "*" + length.stripTrailingZeros().toPlainString();
		String glue = scan.getGlue();
		String remark = scan.getRemark();
		String roll = scan.getRoll();
		String grams = scan.getGrams();
		String labelId = scan.getLabelId();
		material.setLength(length);
		material.setWidth(width);
		material.setCategoryId(categoryId);
		material.setCustomerId(customerId);
		material.setRemark(remark);
		material.setName(category.getName());
		material.setModel(model);
		
		BigDecimal square = width.multiply(length).divide(BigDecimal.valueOf(100L), 4, BigDecimal.ROUND_DOWN);
		material.setSquare(square);
		if(unit.getName().equals("平方")) {
			material.setQuantity(square);
		}
		this.materialService.updateById(material);
		temp.setLength(length);
		temp.setWidth(width);
		temp.setCategoryId(categoryId);
		temp.setName(category.getName());
		temp.setRemark(remark);
		temp.setCustomerId(customerId);
		temp.setGluePosition(glue);
		temp.setRollDirect(roll);
		temp.setGrams(grams);
		temp.setSquare(square);
		temp.setModel(model);
		if(StringUtils.isBlank(labelId)) {
			temp.setLabelId(null);
		} else {
			temp.setLabelId(labelId);
		}
		if(unit.getName().equals("平方")) {
			temp.setAmount(square);
		}
		this.materialTempService.updateById(temp);
		//修改库存
		StkInventory updInventory = null;
		List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).list();
		if(CollUtil.isNotEmpty(inventoryList)) {
			for (StkInventory inventory : inventoryList) {
				String inventoryUnitId = inventory.getUnitId();
				BasMeasureUnit inventoryUnit = this.unitService.getById(inventoryUnitId);
				inventory.setWidth(width);
				inventory.setLength(length);
				String unitName = inventoryUnit.getName();
				if("平方".equals(unitName)) {
					inventory.setQty(square);
				}
				this.inventoryService.updateById(inventory);
				updInventory = inventory;
				break;
			}
		}
		
		List<StkIoBillEntry> entryList = billEntryService.selectByMaterial(material.getId());
		if(CollUtil.isNotEmpty(entryList) && updInventory != null) {
			for(StkIoBillEntry stkIoBillEntry : entryList) {
				StkIoBill mBill = this.billService.getById(stkIoBillEntry.getMid());
				if(ScanServiceImpl.inTypes.contains(mBill.getStockIoType())) {
					stkIoBillEntry.setQty(updInventory.getQty());
					this.billEntryService.updateById(stkIoBillEntry);
				}
			}
		}
		
		Map<String, Object> resultMap = Maps.newHashMap();
		String dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "A";
		resultMap.put("glue", temp.getGluePosition());
		resultMap.put("name", category.getName());
		resultMap.put("code", temp.getCode());
		resultMap.put("model", temp.getModel());
		if(unit != null) {
			resultMap.put("unit", unit.getName());
		}
		//查询设备并判断
		String deviceId = order.getMachineId();
		ZzDevice device = this.deviceService.getById(deviceId);
		String mathineName = "";
		if(null != device) {
			mathineName = device.getDeviceName();
		}
		resultMap.put("number", square);
		resultMap.put("workNo", temp.getInspector());
		resultMap.put("date", dateStr);
		resultMap.put("machine", mathineName);
		resultMap.put("remark", temp.getRemark());
		
		if(null != customer) {
			String customerName = customer.getName();
			customerName = StringUtils.replace(customerName, "\n", "");
			customerName = StringUtils.replace(customerName, "\r", "");
			resultMap.put("customer", customerName);
		} else {
			resultMap.put("customer", StringUtils.EMPTY);
		}
		String preMaterial = "";
		String formulaId = temp.getFormulaId();
		BasProductFormula formula = this.formulaService.getById(formulaId);
		if(formula != null) {
			preMaterial = formula.getPfName();
		}
		resultMap.put("preMaterial", preMaterial.trim());
		
		result.setSuccess(Boolean.TRUE);
		result.setCode(CommonConstant.SC_OK_200);
		result.setResult(resultMap);
		return result;
	}

	@Override
	public Result<Map<String, Object>> rePrintFq(ScanIO scan) {
		Result<Map<String, Object>> result = new Result<>();
		String code = scan.getCode();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == material || null == temp) {
			return result.error500("未找到相关物料");
		}
		String materialId = material.getId();
		Integer count = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).count();
		if(count <= 0) {
			return result.error500("物料库存不足");
		}
		String orderId = temp.getOrderId();
		if(StringUtils.isBlank(orderId)) {
			return result.error500("该物料不是分切入库物料");
		}
		ZrkQzOrder order = this.mesService.getById(orderId);
		if(null == order) {
			return result.error500("该物料不是分切入库物料");
		}
		//判断工序是否正确
		String processId = order.getProcessId();
		ZzDeviceType deviceType = this.deviceTypeService.getById(processId);
		String deviceTpyeName = deviceType.getDeviceTpyeName();
		if(!deviceTpyeName.contains("分切")) {
			return result.error500("该物料不是分切入库物料");
		}
		String categoryId = scan.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return result.error500("请选择物料分类");
		}
		String unitId = category.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		
		String customerId = scan.getCustomerId();
		BasCustomer customer = null;
		if(StringUtils.isNotBlank(customerId)) {
			customer = this.customerMapper.selectById(customerId);
		}
		Integer knife = scan.getKnife();
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String model = width.stripTrailingZeros().toPlainString() + "*" + length.stripTrailingZeros().toPlainString();
		String layerStr = scan.getSurfaceLayer();
		String remark = scan.getRemark();
		String labelId = scan.getLabelId();
		material.setLength(length);
		material.setWidth(width);
		material.setCategoryId(categoryId);
		material.setCustomerId(customerId);
		material.setRemark(remark);
		material.setModel(model);
		material.setName(category.getName());
		BigDecimal square = width.multiply(length).divide(BigDecimal.valueOf(100L), 4, BigDecimal.ROUND_DOWN);
		material.setSquare(square);
		if(unit.getName().equals("平方")) {
			material.setQuantity(square);
		}
		this.materialService.updateById(material);
		temp.setLength(length);
		temp.setWidth(width);
		temp.setCategoryId(categoryId);
		temp.setName(category.getName());
		temp.setRemark(remark);
		temp.setCustomerId(customerId);
		temp.setSquare(square);
		temp.setSupplierId(layerStr);
		temp.setModel(model);
		temp.setKnifeNum(knife);
		if(StringUtils.isBlank(labelId)) {
			temp.setLabelId(null);
		} else {
			temp.setLabelId(labelId);
		}
		if(unit.getName().equals("平方")) {
			temp.setAmount(square);
		}
		this.materialTempService.updateById(temp);
		StkInventory updInventory = null;
		List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).list();
		
		if(CollUtil.isNotEmpty(inventoryList)) {
			for (StkInventory inventory : inventoryList) {
				String inventoryUnitId = inventory.getUnitId();
				BasMeasureUnit inventoryUnit = this.unitService.getById(inventoryUnitId);
				inventory.setWidth(width);
				inventory.setLength(length);
				String unitName = inventoryUnit.getName();
				if("平方".equals(unitName)) {
					inventory.setQty(square);
				}
				this.inventoryService.updateById(inventory);
				updInventory = inventory;
				break;
			}
		}
		
		List<StkIoBillEntry> entryList = billEntryService.selectByMaterial(material.getId());
		if(CollUtil.isNotEmpty(entryList) && updInventory != null) {
			for(StkIoBillEntry stkIoBillEntry : entryList) {
				StkIoBill mBill = this.billService.getById(stkIoBillEntry.getMid());
				if(ScanServiceImpl.inTypes.contains(mBill.getStockIoType())) {
					stkIoBillEntry.setQty(updInventory.getQty());
					this.billEntryService.updateById(stkIoBillEntry);
				}
			}
		}
		
		String pid = temp.getPid();
		String preGlue = null;
		String preRoll = null;
		String prePrint = null;
//		String preGrams = null;
		
		Map<String, Object> resultMap = Maps.newHashMap();
		String dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "B";
		String[] strs = StringUtils.split(pid, ",");
		if(strs.length > 0) {
			pid = strs[0];
		}
		if(StringUtils.isNotBlank(pid)) {
			String[] pidArray = StringUtils.split(pid, ",");
			String mPId = pidArray[0];
			BasMaterial mate = this.materialService.getById(mPId);
			if(null != mate) {
				String preCode = mate.getCode();
				BasMaterialTemp preTemp = this.materialTempService.getByCode(preCode);
				
				preGlue = preTemp.getGluePosition();
				preRoll = preTemp.getRollDirect();
				prePrint = preTemp.getIsPrint();
//				preGrams = preTemp.getGrams();
				
				Date preTime = mate.getCreateTime();
				String preTimeString = ScanUtil.changeDateToString(preTime) + "A";
				resultMap.put("fhTime", preTimeString);
				resultMap.put("roll", preRoll);
				resultMap.put("glue", preGlue);
				String machineId = preTemp.getMachine();
				if(StringUtils.isNotBlank(machineId)) {
					ZzDevice zzDevice = this.deviceService.getById(machineId);
					if(zzDevice != null) {
						resultMap.put("preMachine", zzDevice.getDeviceName());
					}
				}
				resultMap.put("isPrint", prePrint);
			}
		}
		
		String roll = scan.getRoll();
		if(roll == null) {
			roll = StringUtils.EMPTY;
		}
		Integer knifeNum = temp.getKnifeNum();
		resultMap.put("knife", null == knifeNum ? StringUtils.EMPTY : knifeNum.toString());	
		
		resultMap.put("glue", temp.getGluePosition());
		resultMap.put("name", category.getName());
		resultMap.put("code", temp.getCode());
		resultMap.put("model", temp.getModel());
		if(unit != null) {
			resultMap.put("unit", unit.getName());
		}
		//查询设备并判断
		String deviceId = order.getMachineId();
		ZzDevice device = this.deviceService.getById(deviceId);
		String mathineName = "";
		if(null != device) {
			mathineName = device.getDeviceName();
		}
		resultMap.put("number", square);
		resultMap.put("workNo", temp.getInspector());
		resultMap.put("date", dateStr);
		resultMap.put("machine", mathineName);
		resultMap.put("remark", temp.getRemark());
		
		if(null != customer) {
			String customerName = customer.getName();
			customerName = StringUtils.replace(customerName, "\n", "");
			customerName = StringUtils.replace(customerName, "\r", "");
			resultMap.put("customer", customerName);
		} else {
			resultMap.put("customer", StringUtils.EMPTY);
		}
		String preMaterial = "";
		String formulaId = temp.getFormulaId();
		BasProductFormula formula = this.formulaService.getById(formulaId);
		if(formula != null) {
			preMaterial = formula.getPfName();
		}
		resultMap.put("preMaterial", preMaterial.trim());
		
		result.setSuccess(Boolean.TRUE);
		result.setCode(CommonConstant.SC_OK_200);
		result.setResult(resultMap);
		return result;
	}

	@Override
	public Result<Map<String, Object>> rePrintQz(ScanIO scan) {
		Result<Map<String, Object>> result = new Result<>();
		String code = scan.getCode();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == material || null == temp) {
			return result.error500("未找到相关物料");
		}
		String materialId = material.getId();
		Integer count = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).count();
		if(count <= 0) {
			return result.error500("物料库存不足");
		}
		String orderId = temp.getOrderId();
		if(StringUtils.isBlank(orderId)) {
			return result.error500("该物料不是切张入库物料");
		}
		ZrkQzOrder order = this.mesService.getById(orderId);
		if(null == order) {
			return result.error500("该物料不是切张入库物料");
		}
		//判断工序是否正确
		String processId = order.getProcessId();
		ZzDeviceType deviceType = this.deviceTypeService.getById(processId);
		String deviceTpyeName = deviceType.getDeviceTpyeName();
		if(!deviceTpyeName.contains("切张")) {
			return result.error500("该物料不是切张入库物料");
		}
		String categoryId = scan.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return result.error500("请选择物料分类");
		}
		String unitId = category.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		String numberStr = scan.getNumber();
		if(StringUtils.isBlank(numberStr)) {
			return result.error500("请输入张数");
		}
		BigDecimal pageNum = new BigDecimal(numberStr);
		
		String customerId = scan.getCustomerId();
		BasCustomer customer = null;
		if(StringUtils.isNotBlank(customerId)) {
			customer = this.customerMapper.selectById(customerId);
		}
		BigDecimal length = scan.getLength();
		BigDecimal width = scan.getWidth();
		String model = width.stripTrailingZeros().toPlainString() + "*" + length.stripTrailingZeros().toPlainString();
		String remark = scan.getRemark();
		material.setLength(length);
		material.setWidth(width);
		material.setCategoryId(categoryId);
		material.setCustomerId(customerId);
		material.setRemark(remark);
		material.setModel(model);
		material.setName(category.getName());
		material.setViceQuantity(pageNum);
		BigDecimal decimal10000 = BigDecimal.valueOf(10000L);
		BigDecimal square = width.multiply(length).multiply(pageNum).divide(decimal10000, 4, BigDecimal.ROUND_DOWN);
		material.setSquare(square);
		if(unit.getName().equals("平方")) {
			material.setQuantity(square);
		}
		this.materialService.updateById(material);
		String labelId = scan.getLabelId();
		temp.setLength(length);
		temp.setWidth(width);
		temp.setCategoryId(categoryId);
		temp.setName(category.getName());
		temp.setRemark(remark);
		temp.setCustomerId(customerId);
		temp.setSquare(square);
		temp.setModel(model);
		temp.setPageNum(pageNum);
		if(StringUtils.isBlank(labelId)) {
			temp.setLabelId(null);
		} else {
			temp.setLabelId(labelId);
		}
		if(unit.getName().equals("平方")) {
			temp.setAmount(square);
		}
		this.materialTempService.updateById(temp);
		
		List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).list();
		StkInventory updInventory = null;
		if(CollUtil.isNotEmpty(inventoryList)) {
			for (StkInventory inventory : inventoryList) {
				String inventoryUnitId = inventory.getUnitId();
				BasMeasureUnit inventoryUnit = this.unitService.getById(inventoryUnitId);
				inventory.setWidth(width);
				inventory.setLength(length);
				String unitName = inventoryUnit.getName();
				if("平方".equals(unitName)) {
					inventory.setQty(square);
				}
				this.inventoryService.updateById(inventory);
				updInventory = inventory;
				break;
			}
		}
		
		List<StkIoBillEntry> entryList = billEntryService.selectByMaterial(material.getId());
		if(CollUtil.isNotEmpty(entryList) && updInventory != null) {
			for(StkIoBillEntry stkIoBillEntry : entryList) {
				StkIoBill mBill = this.billService.getById(stkIoBillEntry.getMid());
				if(ScanServiceImpl.inTypes.contains(mBill.getStockIoType())) {
					stkIoBillEntry.setQty(updInventory.getQty());
					this.billEntryService.updateById(stkIoBillEntry);
				}
			}
		}
		
		String pid = temp.getPid();
		Map<String, String> qzMap = Maps.newHashMap();
		if(StringUtils.isNotBlank(pid)) {
			String[] pidArray = StringUtils.split(pid, ",");
			String mPId = pidArray[0];
			BasMaterial mate = this.materialService.getById(mPId);
			if(null != mate) {
				String preCode = mate.getCode();
				BasMaterialTemp preTemp = this.materialTempService.getByCode(preCode);
				if(null != preTemp) {
					qzMap.put("fqRoll", StringUtils.isBlank(preTemp.getRollDirect()) ? StringUtils.EMPTY : preTemp.getRollDirect());
					qzMap.put("fqKnife", preTemp.getKnifeNum() != null ? preTemp.getKnifeNum().toString() : StringUtils.EMPTY);
					qzMap.put("fqIn", StringUtils.isBlank(preTemp.getInspector()) ? StringUtils.EMPTY : preTemp.getInspector());
					
				}
				
				String pid2 = preTemp.getPid();
				if(StringUtils.isNotBlank(pid2)) {
					String[] pidArray2 = StringUtils.split(pid2, ",");
					String mPId2 = pidArray2[0];
					BasMaterial mate2 = this.materialService.getById(mPId2);
					if(null != mate2) {
						String code2 = mate2.getCode();
						BasMaterialTemp temp2 = this.materialTempService.getByCode(code2);
						if(null != temp2) {
							qzMap.put("fhRoll", StringUtils.isBlank(temp2.getRollDirect()) ? StringUtils.EMPTY : temp2.getRollDirect());
						}
					}
				}
			}
		}
		
		Map<String, Object> resultMap = Maps.newHashMap();
		String dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "C";
		String[] strs = StringUtils.split(pid, ",");
		if(strs.length > 0) {
			pid = strs[0];
		}
		BasMaterial fqMaterial = this.materialService.getById(pid);
		if(null != fqMaterial) {
			Date preTime = fqMaterial.getCreateTime();
			String preTimeString = ScanUtil.changeDateToString(preTime) + "B";
			resultMap.put("fqTime", preTimeString);
			String fqCode = fqMaterial.getCode();
			BasMaterialTemp preTemp = this.materialTempService.getByCode(fqCode);
			String prePid = preTemp.getPid();
			if(StringUtils.isNotBlank(prePid)) {
				String[] preStrs = StringUtils.split(prePid, ",");
				if(preStrs.length > 0) {
					prePid = preStrs[0];
				}
			}
			BasMaterial fhMaterial = this.materialService.getById(prePid);
			if(fhMaterial != null) {
				Date fhTime = fhMaterial.getCreateTime();
				String fhTimeStr = ScanUtil.changeDateToString(fhTime) + "A";
				resultMap.put("fhTime", fhTimeStr);
			}
		}
//		resultMap.put("preCode", code);
		Integer knifeNum = temp.getKnifeNum();
		resultMap.put("knife", null == knifeNum ? StringUtils.EMPTY : knifeNum.toString());
		
		resultMap.put("fqRoll", null == qzMap.get("fqRoll") ? StringUtils.EMPTY : qzMap.get("fqRoll"));
		resultMap.put("fqKnife", null == qzMap.get("fqKnife") ? StringUtils.EMPTY : qzMap.get("fqKnife"));
		resultMap.put("fqIn", null == qzMap.get("fqIn") ? StringUtils.EMPTY : qzMap.get("fqIn"));
		resultMap.put("fhRoll", null == qzMap.get("fhRoll") ? StringUtils.EMPTY : qzMap.get("fhRoll"));
		
		resultMap.put("glue", temp.getGluePosition());
		resultMap.put("name", category.getName());
		resultMap.put("code", temp.getCode());
		resultMap.put("model", temp.getModel());
		if(StringUtils.isNotBlank(numberStr)) {
			resultMap.put("paperNum", numberStr);
		}
		if(unit != null) {
			resultMap.put("unit", unit.getName());
		}
		//查询设备并判断
		String deviceId = order.getMachineId();
		ZzDevice device = this.deviceService.getById(deviceId);
		String mathineName = "";
		if(null != device) {
			mathineName = device.getDeviceName();
		}
		resultMap.put("number", square);
		resultMap.put("workNo", temp.getInspector());
		resultMap.put("date", dateStr);
		resultMap.put("machine", mathineName);
		resultMap.put("remark", temp.getRemark());
		
		if(null != customer) {
			String customerName = customer.getName();
			customerName = StringUtils.replace(customerName, "\n", "");
			customerName = StringUtils.replace(customerName, "\r", "");
			resultMap.put("customer", customerName);
		} else {
			resultMap.put("customer", StringUtils.EMPTY);
		}
		result.setSuccess(Boolean.TRUE);
		result.setCode(CommonConstant.SC_OK_200);
		result.setResult(resultMap);
		return result;
	}

	@Override
	public Result<?> rePrintCategory() {
		List<BasMaterialCategory> list = this.categoryService.lambdaQuery().eq(BasMaterialCategory::getIsEnabled, Integer.valueOf(1)).orderByAsc(BasMaterialCategory::getName).list();
		list = ScanUtil.changeListToVector(list);
		return Result.ok(list);
	}

	@Override
	public Result<?> rePrintGetMaterial(String code) {
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == temp) {
			return Result.error("未找到相关物料");
		}
		BasMaterial material = this.materialService.getMaterialByCode(temp.getCode());
		if(null == material) {
			return Result.error("未找到相关物料");
		}
		String orderId = temp.getOrderId();
		if(StringUtils.isNotBlank(orderId)) {
			ZrkQzOrder mes = this.mesService.getById(orderId);
			if(null != mes) {
				String mesCode = mes.getCode();
				temp.setOrderId(mesCode);
			}
		}
		List<StkInventory> list = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, material.getId()).list();
		for (StkInventory stkInventory : list) {
			BigDecimal qty = stkInventory.getQty();
			if(qty.compareTo(BigDecimal.ZERO) > 0) {
				temp.setAmount(qty);
			}
		}
		
		return Result.ok(temp);
	}

	@Override
	public Result<?> getCodeCustomer(String code) {
		if(StringUtils.isBlank(code)) {
			return Result.ok();
		}
		//判断编码是否为托盘码
		List<String> materialIdList = Lists.newArrayList();
		BasCustomer customer = null;
		if(ScanUtil.isTrayCode(code)) {
			StkTray tray = this.trayService.getTrayByCode(code);
			if(null != tray) {
				String customerId = tray.getCustomerId();
				customer = this.customerMapper.selectById(customerId);
				List<StkTrayDetail> detailList = this.trayDetailService.selectByMainId(tray.getId());
				if(CollUtil.isNotEmpty(detailList)) {
					for (StkTrayDetail detail : detailList) {
						materialIdList.add(detail.getMaterialId());
					}
				}
			}
		} else {
			BasMaterial material = this.materialService.getMaterialByCode(code);
			if(null != material) {
				String customerId = material.getCustomerId();
				customer = this.customerMapper.selectById(customerId);
				materialIdList.add(material.getId());
			}
		}
		materialIdList.add(IdUtil.randomUUID());
		List<BasMaterial> materialList = this.materialService.listByIds(materialIdList);
		Map<String, Object> resultMap = Maps.newHashMap();
		if(null != customer) {
			resultMap.put("name", customer.getName());
			resultMap.put("id", customer.getId());
		}
		resultMap.put("list", materialList);
		return Result.ok(resultMap);
	}

	@Override
	public Result<?> purchaseReturnMaterial(String code) {
		BasMaterial material = this.materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到物料");
		}
		String materialId = material.getId();
		List<StkIoBillEntry> entryList = this.billEntryService.lambdaQuery().eq(StkIoBillEntry::getMaterialId, materialId).list();
		if(CollUtil.isEmpty(entryList)) {
			return Result.error("没有该物料的出入库记录");
		}
		HashSet<String> midSet = Sets.newHashSet();
		for (StkIoBillEntry entry : entryList) {
			String mid = entry.getMid();
			if(!midSet.contains(mid)) {
				midSet.add(mid);
			}
		}
		if(midSet.isEmpty()) {
			midSet.add(IdUtil.fastSimpleUUID());
		}
		List<StkIoBill> billList = this.billService.lambdaQuery().eq(StkIoBill::getStockIoType, "101").in(StkIoBill::getId, midSet).list();
		if(CollUtil.isEmpty(billList)) {
			return Result.error("没有该物料的出入库记录");
		}
		StkIoBill bill = billList.get(0);
		String billId = bill.getId();
		List<StkIoBillEntry> billEntryList = this.billEntryService.lambdaQuery().eq(StkIoBillEntry::getMid, billId).list();
		if(CollUtil.isEmpty(billEntryList)) {
			return Result.error("没有该物料的出入库记录");
		}
		StkIoBillEntry billEntry = null;
		for (StkIoBillEntry entry : billEntryList) {
			if(materialId.equals(entry.getMaterialId())) {
				billEntry = entry;
				break;
			}
		}
		String supplierId = bill.getSupplierId();
		if(null == supplierId) {
			return Result.error("未找到供应商");
		}
		String sourceNo = bill.getSourceNo();
		if(StringUtils.isBlank(sourceNo)) {
			return Result.error("未找物料相关的采购单");
		}
		List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).list();
		if(CollUtil.isEmpty(inventoryList)) {
			return Result.error("未找到物料相关的库存记录");
		}
		StkInventory inventory = inventoryList.get(0);
		String warehouseId = inventory.getWarehouseId();
		BasWarehouse warehouse = this.warehouseService.getById(warehouseId);
		String unitId = material.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		BasSupplier supplier = this.supplierService.getById(supplierId);
		
		Map<String, String> result = Maps.newHashMap();
		result.put("materialId", materialId);
		if(warehouse != null) {
			result.put("warehouseId", warehouseId);
			result.put("warehouseName", warehouse.getName());
		}
		if(unit != null) {
			result.put("unitId", unitId);
			result.put("unitName", unit.getName());
		}
		if(supplier != null) {
			result.put("supplierId", supplierId);
			result.put("supplierName", supplier.getName());
		}
		BigDecimal width = material.getWidth();
		BigDecimal length = material.getLength();
		if(null != width) {
			result.put("width", width.toPlainString());
		} else {
			result.put("width", StringUtils.EMPTY);
		}
		if(null != length) {
			result.put("length", length.toPlainString());
		} else {
			result.put("length", StringUtils.EMPTY);
		}
		result.put("inventoryId", inventory.getId());
		result.put("billId", bill.getId());
		if(null != billEntry) {
			result.put("entryId", billEntry.getId());
		} else {
			result.put("entryId", StringUtils.EMPTY);
		}
		BigDecimal qty = inventory.getQty();
		BigDecimal cost = inventory.getCost();
		if(null != qty) {
			result.put("qty", qty.toPlainString());
		} else {
			result.put("qty", StringUtils.EMPTY);
		}
		if(null != cost) {
			result.put("cost", cost.toPlainString());
		} else {
			result.put("cost", StringUtils.EMPTY);
		}
		return Result.ok(result);
	}

	@Override
	public Result<?> purchaseReturn(ScanIO scan) {
		String materialId = scan.getMaterialId();
		String code = scan.getCode();
		BasMaterial material = materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到物料");
		}
		if(StringUtils.isBlank(materialId)) {
			return Result.error("未传入物料ID");
		}
		if(!materialId.equals(material.getId())) {
			return Result.error("传入的物料ID跟物料不符");
		}
		BigDecimal width = scan.getWidth();
		BigDecimal length = scan.getLength();
		BigDecimal amount = scan.getAmount();
		String numberStr = scan.getNumber();
		String unitId = material.getUnitId();
		//根据物料查询相关的出入库、库存、供应商、仓库信息
		List<StkIoBillEntry> entryList = this.billEntryService.lambdaQuery().eq(StkIoBillEntry::getMaterialId, materialId).list();
		if(CollUtil.isEmpty(entryList)) {
			return Result.error("没有该物料的出入库记录");
		}
		HashSet<String> midSet = Sets.newHashSet();
		for (StkIoBillEntry entry : entryList) {
			String mid = entry.getMid();
			if(!midSet.contains(mid)) {
				midSet.add(mid);
			}
		}
		if(midSet.isEmpty()) {
			midSet.add(IdUtil.fastSimpleUUID());
		}
		List<StkIoBill> billList = this.billService.lambdaQuery().eq(StkIoBill::getStockIoType, "101").in(StkIoBill::getId, midSet).list();
		if(CollUtil.isEmpty(billList)) {
			return Result.error("没有该物料的出入库记录");
		}
		StkIoBill bill = billList.get(0);
		String billId = bill.getId();
		List<StkIoBillEntry> billEntryList = this.billEntryService.lambdaQuery().eq(StkIoBillEntry::getMid, billId).list();
		if(CollUtil.isEmpty(billEntryList)) {
			return Result.error("没有该物料的出入库记录");
		}
		StkIoBillEntry billEntry = null;
		for (StkIoBillEntry entry : billEntryList) {
			if(materialId.equals(entry.getMaterialId())) {
				billEntry = entry;
				break;
			}
		}
		if(null == billEntry) {
			return Result.error("没有该物料的出入库记录");
		}
		String supplierId = bill.getSupplierId();
		if(null == supplierId) {
			return Result.error("未找到供应商");
		}
		String sourceNo = bill.getSourceNo();
		if(StringUtils.isBlank(sourceNo)) {
			return Result.error("未找物料相关的采购单");
		}
		List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).list();
		if(CollUtil.isEmpty(inventoryList)) {
			return Result.error("未找到物料相关的库存记录");
		}
		StkInventory inventory = inventoryList.get(0);
		String warehouseId = inventory.getWarehouseId();
		//
		StkIoBill returnBill = new StkIoBill();
		String billNo = baseApi.getNoByCode("stock_io_bill_no");
		returnBill.setBillNo(billNo);
		
		return null;
	}

	@Override
	public Result<?> splitQzMaterial(String code) {
		BasMaterial material = materialService.getMaterialByCode(code);
		if(null == material) {
			return Result.error("未找到物料");
		}
		BigDecimal width = material.getWidth();
		BigDecimal length = material.getLength();
		BigDecimal quantity = material.getViceQuantity();
		
		Map<String, String> map = Maps.newHashMap();
		map.put("width", width == null ? StringUtils.EMPTY : width.toPlainString());
		map.put("length", length == null ? StringUtils.EMPTY : length.toPlainString());
		map.put("quantity", quantity == null ? StringUtils.EMPTY : quantity.toPlainString());
		return Result.ok(map);
	}

	@Override
	@Transactional
	public Result<?> splitQz(ScanIO scan) {
		synchronized (this) {
			String code = scan.getCode();
			BasMaterial material = this.materialService.getMaterialByCode(code);
			if(null == material) {
				return Result.error("未找到物料");
			}
			
			String numberStr = scan.getNumber();
			BigDecimal number = null;
			try {
				number = new BigDecimal(numberStr);
			} catch (Exception e) {
				e.printStackTrace();
				return Result.error("输入的数量不是数字");
			}
			BigDecimal amount = material.getViceQuantity();
			if(number.compareTo(amount) >= 0 || number.compareTo(BigDecimal.ZERO) <=0) {
				return Result.error("输入的张数不是正整数");
			}
			BasMaterialTemp temp = this.materialTempService.getByCode(code);
			if(temp == null) {
				return Result.error("未找到物料。");
			}
			String mesId = temp.getProcedureId();
			ZrkQzOrder mes = this.mesService.getById(mesId);
			if(mes == null) {
				return Result.error("未找到物料工序。");
			}
			String processId = mes.getProcessId();
			ZzDeviceType deviceType = this.deviceTypeService.getById(processId);
			String processName = deviceType.getDeviceTpyeName() == null ? StringUtils.EMPTY : deviceType.getDeviceTpyeName();
			if(!StringUtils.contains(processName, "切张")) {
				return Result.error("该物料不是切张产品");
			}
			String materialId = material.getId();
			List<StkInventory> inventoryList = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId)
					.gt(StkInventory::getQty, BigDecimal.ZERO).list();
			if(CollUtil.isEmpty(inventoryList)) {
				return Result.error("未找到物料的库存记录");
			}
			List<StkIoBill> billList = billMapper.selectBatchByMaterialIdList(Lists.newArrayList(materialId), "1991");
			if(CollUtil.isEmpty(billList)) {
				return Result.error("未找到物料的入库单");
			}
			StkIoBill stkIoBill = billList.get(0);
			StkInventory inventory = inventoryList.get(0);
			List<StkIoBillEntry> entryList = billEntryService.lambdaQuery().eq(StkIoBillEntry::getMid, stkIoBill.getId()).list();
			StkIoBillEntry materialEntry = null;
			int entryNo = 0;
			for (StkIoBillEntry entry : entryList) {
				Integer no = entry.getEntryNo();
				if(no > entryNo) {
					entryNo = no;
				}
				String entryMateiralId = entry.getMaterialId();
				if(StringUtils.equals(materialId, entryMateiralId)) {
					materialEntry = entry;
				}
			}
			if(materialEntry == null) {
				return Result.error("未找到物料的入库明细");
			}
			entryNo++;
			int entryBatch = entryNo * 10;
			
			BigDecimal restNum = amount.subtract(number);
			String categoryId = material.getCategoryId();
			BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
			String categoryCode = category.getCode();
			String materialCode = this.materialService.getCode(categoryCode);
			
			BigDecimal width = material.getWidth();
			BigDecimal length = material.getLength();
			
			BigDecimal materialCost = materialEntry.getCost();
			BigDecimal cost1 = BigDecimal.ZERO;
			BigDecimal cost2 = BigDecimal.ZERO;
			if(materialCost.compareTo(BigDecimal.ZERO) > 0) {
				cost1 = number.divide(amount, 40, BigDecimal.ROUND_DOWN).multiply(materialCost);
				cost2 = materialCost.subtract(cost1);
			}
			
			material.setViceQuantity(number);
			temp.setPageNum(number);
			BigDecimal amount1 = width.multiply(length).multiply(number);
			amount1 = amount1.divide(new BigDecimal("10000"), 10, BigDecimal.ROUND_DOWN);
			BigDecimal amount2 = width.multiply(length).multiply(restNum);
			amount2 = amount2.divide(new BigDecimal("10000"), 10, BigDecimal.ROUND_DOWN);
			material.setSquare(amount1);
			material.setQuantity(amount1);
			temp.setSquare(amount1);
			temp.setAmount(amount1);
			this.materialService.updateById(material);
			this.materialTempService.updateById(temp);
			//更新库存及入库记录
			inventory.setQty(amount1);
			materialEntry.setQty(amount1);
			materialEntry.setSettleQty(amount1);
			materialEntry.setCost(cost1);
			inventory.setCost(cost1);
			
			//新增物料信息
			BasMaterial material2 = ObjectUtil.clone(material);
			material2.setId(null);
			material2.setCode(materialCode);
			material2.setViceQuantity(restNum);
			material2.setSquare(amount2);
			material2.setQuantity(amount2);
			BasMaterialTemp temp2 = ObjectUtil.clone(temp);
			temp2.setId(null);
			temp2.setCode(materialCode);
			temp2.setPageNum(restNum);
			temp2.setAmount(amount2);
			temp2.setSquare(amount2);
			this.materialService.save(material2);
			this.materialTempService.save(temp2);
			//新增出入库记录及库存记录
			StkIoBillEntry newEntry = ObjectUtil.clone(materialEntry);
			StkInventory newInventory = ObjectUtil.clone(inventory);
			newEntry.setMaterialId(material2.getId());
			newEntry.setEntryNo(entryNo);
			newEntry.setId(null);
			newEntry.setBatchNo(StrUtil.builder(stkIoBill.getBillNo(), "-").append(entryBatch).toString());
			newEntry.setCost(cost2);
			newInventory.setMaterialId(material2.getId());
			newInventory.setBatchNo(newEntry.getBatchNo());
			newInventory.setId(null);
			newInventory.setCost(cost2);
			this.inventoryService.save(newInventory);
			this.billEntryService.save(newEntry);
			
			List<Map<String, Object>> list = Lists.newArrayList();
			ScanIO scan1 = new ScanIO();
			scan1.setCode(material.getCode());
			scan1.setCategoryId(categoryId);
			scan1.setNumber(material.getViceQuantity().toPlainString());
			scan1.setCustomerId(material.getCustomerId());
			scan1.setWidth(material.getWidth());
			scan1.setLength(material.getLength());
			scan1.setRemark(material.getRemark());
			scan1.setLabelId(temp.getLabelId());
			ScanIO scan2 = new ScanIO();
			scan2.setCode(material2.getCode());
			scan2.setCategoryId(categoryId);
			scan2.setNumber(material2.getViceQuantity().toPlainString());
			scan2.setCustomerId(material2.getCustomerId());
			scan2.setWidth(material2.getWidth());
			scan2.setLength(material2.getLength());
			scan2.setRemark(material2.getRemark());
			scan2.setLabelId(temp2.getLabelId());
			Map<String, Object> map1 = this.getQzPrintMap(scan1);
			Map<String, Object> map2 = this.getQzPrintMap(scan2);
			if(map1 != null) {
				list.add(map1);
			}
			if(map2 != null) {
				list.add(map2);
			}
			return Result.ok(list);	
		}
	}
	
	@Transactional
	private Map<String, Object> getQzPrintMap(ScanIO scan){
		String code = scan.getCode();
		BasMaterial material = this.materialService.getMaterialByCode(code);
		BasMaterialTemp temp = this.materialTempService.getByCode(code);
		if(null == material || null == temp) {
			return null;
		}
		String materialId = material.getId();
		Integer count = this.inventoryService.lambdaQuery().eq(StkInventory::getMaterialId, materialId).gt(StkInventory::getQty, BigDecimal.ZERO).count();
		if(count <= 0) {
			return null;
		}
		String orderId = temp.getOrderId();
		if(StringUtils.isBlank(orderId)) {
			return null;
		}
		ZrkQzOrder order = this.mesService.getById(orderId);
		if(null == order) {
			return null;
		}
		String categoryId = scan.getCategoryId();
		BasMaterialCategory category = this.categoryMapper.selectById(categoryId);
		if(null == category) {
			return null;
		}
		String unitId = category.getUnitId();
		BasMeasureUnit unit = this.unitService.getById(unitId);
		String numberStr = scan.getNumber();
		if(StringUtils.isBlank(numberStr)) {
			return null;
		}
		
		String customerId = scan.getCustomerId();
		BasCustomer customer = null;
		if(StringUtils.isNotBlank(customerId)) {
			customer = this.customerMapper.selectById(customerId);
		}
		
		String pid = temp.getPid();
		Map<String, String> qzMap = Maps.newHashMap();
		if(StringUtils.isNotBlank(pid)) {
			String[] pidArray = StringUtils.split(pid, ",");
			String mPId = pidArray[0];
			BasMaterial mate = this.materialService.getById(mPId);
			if(null != mate) {
				String preCode = mate.getCode();
				BasMaterialTemp preTemp = this.materialTempService.getByCode(preCode);
				if(null != preTemp) {
					qzMap.put("fqRoll", StringUtils.isBlank(preTemp.getRollDirect()) ? StringUtils.EMPTY : preTemp.getRollDirect());
					qzMap.put("fqKnife", preTemp.getKnifeNum() != null ? preTemp.getKnifeNum().toString() : StringUtils.EMPTY);
					qzMap.put("fqIn", StringUtils.isBlank(preTemp.getInspector()) ? StringUtils.EMPTY : preTemp.getInspector());
					
				}
				
				String pid2 = preTemp.getPid();
				if(StringUtils.isNotBlank(pid2)) {
					String[] pidArray2 = StringUtils.split(pid2, ",");
					String mPId2 = pidArray2[0];
					BasMaterial mate2 = this.materialService.getById(mPId2);
					if(null != mate2) {
						String code2 = mate2.getCode();
						BasMaterialTemp temp2 = this.materialTempService.getByCode(code2);
						if(null != temp2) {
							qzMap.put("fhRoll", StringUtils.isBlank(temp2.getRollDirect()) ? StringUtils.EMPTY : temp2.getRollDirect());
						}
					}
				}
			}
		}
		
		Map<String, Object> resultMap = Maps.newHashMap();
		String dateStr = ScanUtil.changeDateToString(material.getCreateTime()) + "C";
		String[] strs = StringUtils.split(pid, ",");
		if(strs.length > 0) {
			pid = strs[0];
		}
		BasMaterial fqMaterial = this.materialService.getById(pid);
		if(null != fqMaterial) {
			Date preTime = fqMaterial.getCreateTime();
			String preTimeString = ScanUtil.changeDateToString(preTime) + "B";
			resultMap.put("fqTime", preTimeString);
			String fqCode = fqMaterial.getCode();
			BasMaterialTemp preTemp = this.materialTempService.getByCode(fqCode);
			String prePid = preTemp.getPid();
			if(StringUtils.isNotBlank(prePid)) {
				String[] preStrs = StringUtils.split(prePid, ",");
				if(preStrs.length > 0) {
					prePid = preStrs[0];
				}
			}
			BasMaterial fhMaterial = this.materialService.getById(prePid);
			if(fhMaterial != null) {
				Date fhTime = fhMaterial.getCreateTime();
				String fhTimeStr = ScanUtil.changeDateToString(fhTime) + "A";
				resultMap.put("fhTime", fhTimeStr);
			}
		}
//		resultMap.put("preCode", code);
		Integer knifeNum = temp.getKnifeNum();
		resultMap.put("knife", null == knifeNum ? StringUtils.EMPTY : knifeNum.toString());
		
		resultMap.put("fqRoll", null == qzMap.get("fqRoll") ? StringUtils.EMPTY : qzMap.get("fqRoll"));
		resultMap.put("fqKnife", null == qzMap.get("fqKnife") ? StringUtils.EMPTY : qzMap.get("fqKnife"));
		resultMap.put("fqIn", null == qzMap.get("fqIn") ? StringUtils.EMPTY : qzMap.get("fqIn"));
		resultMap.put("fhRoll", null == qzMap.get("fhRoll") ? StringUtils.EMPTY : qzMap.get("fhRoll"));
		
		resultMap.put("glue", temp.getGluePosition());
		resultMap.put("name", category.getName());
		resultMap.put("code", temp.getCode());
		resultMap.put("model", temp.getModel());
		if(StringUtils.isNotBlank(numberStr)) {
			resultMap.put("paperNum", numberStr);
		}
		if(unit != null) {
			resultMap.put("unit", unit.getName());
		}
		//查询设备并判断
		String deviceId = order.getMachineId();
		ZzDevice device = this.deviceService.getById(deviceId);
		String mathineName = "";
		if(null != device) {
			mathineName = device.getDeviceName();
		}
		resultMap.put("number", material.getSquare());
		resultMap.put("workNo", temp.getInspector());
		resultMap.put("date", dateStr);
		resultMap.put("machine", mathineName);
		resultMap.put("remark", temp.getRemark());
		
		if(null != customer) {
			String customerName = customer.getName();
			customerName = StringUtils.replace(customerName, "\n", "");
			customerName = StringUtils.replace(customerName, "\r", "");
			resultMap.put("customer", customerName);
		} else {
			resultMap.put("customer", StringUtils.EMPTY);
		}
		String labelId = scan.getLabelId();
		BasCategoryLabel label = this.labelService.getById(labelId);
		resultMap.put("label", label == null ? StringUtils.EMPTY : label.getCategoryLabel());
		
		return resultMap;
	}
}
